I have a UL that contain any number of LIs. I am trying to create some jQuery code that will parse the original UL and wrap a UL and another LI after every 5 of the original LIs.
Starting HTML:
<ul id="original_ul">
<li class="original_li">..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
</ul>
Required HTML:
<ul id="processed_ul">
<li class="new_wrap_li">
<ul class="new_wrap_ul">
<li class="original_li">..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
</ul><!-- end new wrap ul -->
</li><!-- end new wrap li -->
<li class="new_wrap_li">
<ul class="new_wrap_ul">
<li class="original_li">..</li>
<li>..</li>
<li>..</li>
<li>..</li>
<li>..</li>
</ul><!-- end new wrap ul -->
</li><!-- end new wrap li -->
</ul><!-- end processed ul -->
I've been using the .each function to go through the LIs and append them to the new processed ul held inside a temp div... now I just need to wrap the new LI and UL around every 5 LIs.
Thanks in advance!!
Al
To wrap multiple elements in jQuery, use the wrapAll() method. The wrapAll( ) method wraps all the elements in the matched set into a single wrapper element. Here is the description of all the parameters used by this method: html − A string of HTML that will be created on the fly and wrapped around each target.
wrapAll( wrappingElement )Returns: jQuery. Description: Wrap an HTML structure around all elements in the set of matched elements.
The wrap() method wraps specified HTML element(s) around each selected element.
jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector).
You can do this:
var lis = $("#original_ul li");
for(var i = 0; i < lis.length; i+=5) {
lis.slice(i, i+5)
.wrapAll("<li class='new_wrap_li'><ul class='new_wrap_ul'></ul></li>");
}
This keeps them in the same #original_ul
element, but you could just change the ID if that's necessary. This approach generates the exact output html you have in the question aside from the ID on the top <ul>
jQuery('ul#original_ul').attr('id', 'processed_ul')
.find('li:nth-child(5n)').each(function() {
$(this).prevAll('li').andSelf()
.wrapAll('<li class="new_wrap_li"><ul class="new_wrap_ul"></ul></li>');
});
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