Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping range of children elements in a div

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.

like image 544
Zack Brady Avatar asked Jul 10 '12 03:07

Zack Brady


2 Answers

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' />");
like image 55
xdazz Avatar answered Oct 14 '22 01:10

xdazz


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>");
like image 38
Max Hudson Avatar answered Oct 14 '22 02:10

Max Hudson