select certain number of immediate siblings w/ jQuery

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

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!

回答1:

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

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...

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.



回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!