I am having a hard time figuring this out, but I am sure it is simple.
I know that I have to use :nth-child to count every set of elements I want to wrap. I am wondering how I would count to :nth-child and wrap all the previous elements including the :nth-child in a div for each set of elements that match :nth-child. I am assuming there is an .each() involved.
The code would be laid out like so:
<div class="wrapper">
<h3>Heading</h3>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<h3>Heading</h3>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<h3>Heading</h3>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<h3>Heading</h3>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>
Update Tried this piece of code and it seems to give me the desired results, but stops at 16.
$(".wrapper").each( function () {
$(this).children(":lt(16)").wrapAll("<div></div>")
});
jQuery’s
.each()function has a built inindex– so we can use that to our advantage to select every 16 elements.
DEMO http://jsfiddle.net/CRz7E/1/
If you wanted to wrap each element separately – instead of as a group, then you don’t need to reverse the selection, and you could just use
.wrap()