I have an unordered list exported by a CMS and need to identify <li>
elements that have the class .sub and wrap them in a <ul>
.
I have tried the wrapAll()
method but that finds all <li class="sub">
elements and wraps them in one <ul>
. I need it to maintain seperate groupings.
The exported code is as follows:
<ul>
<li></li>
<li></li>
<li></li>
<li class="sub"></li>
<li class="sub"></li>
<li class="sub"></li>
<li></li>
<li></li>
<li class="sub"></li>
<li class="sub"></li>
<li class="sub"></li>
<li></li>
</ul>
I need it to be:
<ul>
<li></li>
<li></li>
<li></li>
<ul>
<li class="sub"></li>
<li class="sub"></li>
<li class="sub"></li>
</ul>
<li></li>
<li></li>
<li></li>
<ul>
<li class="sub"></li>
<li class="sub"></li>
<li class="sub"></li>
</ul>
<li></li>
<li></li>
</ul>
Any help would be greatly appreciated.
.each
to walk through all .sub
elements.wrapped
, using hasClass()
nextUntil(:not(.sub))
to select all consecutive sub elements (include itself using .andSelf()
)..sub
.wrapAll
For completeness, I have wrapped the set of <li>
elements in <li><ul>...</ul></li>
instead of a plain <ul>
.
Code:
$('.sub').each(function() {
if ($(this.parentNode).hasClass('wrapped')) return;
$(this).nextUntil(':not(.sub)').andSelf().wrapAll('<li><ul class="wrapped">');
});
$('ul.wrapped').removeClass('wrapped'); // Remove temporary dummy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With