问题
I'm trying to wrap a range of children elements in div in order to manipulate them in groups; trying to position each group in a different place. The scenario is that I have a list randomly generating li
tags and no matter how many appear I need every set of ten to be manipulated separately.
To figure this out I'm using a written out list:
$("ul li ul li:nth-child(n+11)").wrapAll("<span class='shift' />");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="access">
<div class="menu">
<ul>
<li>
<p>Hello</p>
<ul>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff2</li>
<li>Stuff3</li>
<li>Stuff3</li>
<li>Stuff3</li>
<li>Stuff3</li>
<li>Stuff3</li>
<li>Stuff3</li>
<li>Stuff3</li>
<li>Stuff3</li>
<li>Stuff3</li>
<li>Stuff3</li>
</ul>
</li>
</ul>
</div>
</div>
But this isn't what I need of course.
Here's the code I'm working on now.
var count = $("ul li ul li").length;
for(var c = 11; c<=count;c+=10){
$("ul li ul li:nth-child(n+"+c+")").wrapAll("<span class='shift' />");
}
This kind of works but it creates nested instances of the shift class.
I need separate wrapper divs. If I was to make up code it would be:
$("ul li ul li:nth-child("+c+"<n<"+(c+10)+")").wrapAll("<span class='shift' />");
But obviously that won't work. Anyone else do something like this before. Been searching a bit with no success.
回答1:
You could try .slice method:
// note: different from nth-child, slice is 0-based position
$("ul li ul li").slice(c, c+10).wrapAll("<span class='shift' />");
回答2:
var i=0;
$(".menu ul ul li:first-child").before("<div>");
$(".menu ul ul li").each(function(){
i++;
if(i % 10==0){
$(this).after('</div><div>')
}
});
$(".menu ul ul li:last-child").after("</div>");
来源:https://stackoverflow.com/questions/11406109/wrapping-range-of-children-elements-in-a-div