I have an unordered list that needs to be spilit into a hierachal list, depending on the class that has been pre-assigned to each
<ul>
<li class="level-1"><a href="#">First Level Item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-1"><a href="#">Next First Level Item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
</ul>
I need it to become a nested list based on the class of each li so the final list is renedered as:
<ul>
<li class="level-1"><a href="#">First Level Item</a>
<ul>
<li class="level-2"><a href="#">Second Level item</a>
<ul>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
</ul>
</li>
<li class="level-2"><a href="#">Second Level item</a>
<ul>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
</ul>
</li>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a></li>
</ul>
</li>
<li class="level-1"><a href="#">Next First Level Item</a>
<ul>
<li class="level-2"><a href="#">Second Level item</a></li>
<li class="level-2"><a href="#">Second Level item</a>
<ul>
<li class="level-3"><a href="#">Third Level item</a></li>
<li class="level-3"><a href="#">Third Level item</a></li>
</ul>
</li>
</ul>
</ul>
Because I can't run server-side code on the CMS that is outputting this list, I must reorganize this HTML list client side.
I've spent many hours without luck trying to write my own jQuery to create the new hierachy. My first attempt was trying to use a jQuery .before to add the additional </ul></li>
tags before a class, and then append a new <ul>
after the tag, but I wasn't able to get any <ul> <li>
tags inserted -- seems jquery will add a <p>
etc. but not a </ul></li>
?
I then tried using a .wrap to put a new <ul></ul>
where needed but I haven't been clever enough to figure out how to just select and group all the children or grandchildren to wrap.
Anyone have any hints on what I should be trying to do?