简体   繁体   中英

select certain number of immediate siblings w/ jQuery

I have multiple divs like this:

<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>

<div class="large"></div>
<div class="large"></div>

<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>

I want to select every 4 .small divs to wrap in another div so it's like this:

<div class="box">
    <div class="small"></div>
    <div class="small"></div>
    <div class="small"></div>
    <div class="small"></div>
</div>

As you can see from the first example, there can be more than 4 adjacent ones, but I still want to group every 4 .small divs.

Any idea would be much appreciated. Thanks!

Here is how I've done it in the past.

var smallDivs = $('div.small'),
    chunkLength = 4;

for (var i = 0, length = smallDivs.length; i < length; i += chunkLength) {
    smallDivs.slice(i, i + chunkLength).wrapAll('<div class="box" />');
}​

jsFiddle .

I chunk the selected elements into chunks of a desired length and then call wrapAll() on the sub-selection.

Just for the hell of it, here is how you'd do it without jQuery...

var smallDivs = document.querySelectorAll('div.small'),
    chunkLength = 4,
    box;

for (var i = 0, length = smallDivs.length; i < length; i++) {
    if (!(i % chunkLength)) {
        box = document.createElement('div');
        box.className = 'box';
        smallDivs[i].parentNode.appendChild(box);
    }

    box.appendChild(smallDivs[i]);

}​

jsFiddle .

Of course, for old browsers that don't support document.querySelectorAll() or document.getElementsByClassName() , replace the element selecting code with...

var divs = document.getElementsByTagName('div'),
    smallDivs = [];

for (var i = 0, length = divs.length; i < length; i++) {
    if ((' ' + divs[i].className + ' ').indexOf(' small ') >= 0) {
        smallDivs.push(divs[i]);
    }
}

jsFiddle .

You use slice or gt() and lt() See example below

$(".small").slice(4,10).wrapAll('<div class"smallWrapper"></div>');

Or

$(".small:gt(5):lt(10)").wrapAll('<div class"smallWrapper">

jsfiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM