I need to get some list elements inside of wrapper div/span. This is h开发者_高级运维ow it is now:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
</ul>
What I need is something like this:
<ul>
<div class="wrapper">
<li>One</li>
<li>Two</li>
</div><div class="wrapper">
<li>Three</li>
<li>Four</li>
</div><div class="wrapper">
<li>Five</li>
<li>Six</li>
<div class="wrapper">
</ul>
Or that can be somthing like span. Doesnt really matter. BUt I need to wrap after every three li elements.
You can iterate over your elements and wrap them using .slice()
and .wrapAll()
, like this:
var lis = $("ul li");
for(var i = 0; i < lis.length; i+=3) {
lis.slice(i, i+3).wrapAll('<li class="wrapper"><ul></ul></li>');
}
Since you said something like a <div>
/<span>
this will do the job, and give you valid HTML, like this:
<ul>
<li class="wrapper">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</li>
<li class="wrapper">
<ul>
<li>Four</li>
<li>Five</li>
<li>Six</li>
</ul>
</li>
</ul>
Your example showed every 2 elements, but your question text said every 3...I just picked 3 here, just adjust the number in the function and you're all set.
It is not valid HTML and it is wrong to do it - You cannot insert div inside list, but I will give for future reference the syntax of wrapping in jQuery:
$("JQUERYSELECTOR").wrap("<div class='wrapper'></div>");
The JQUERYSELECTOR should be whatever elements that you want to wrap i.e
#ul:nth-child(1)
for the first child of the list.
But again, wrapping div on list items is wrong.
精彩评论