开发者

wrapping elements in a new div

开发者 https://www.devze.com 2023-02-08 22:19 出处:网络
I have the below html: <div id=\"one\"> <div class=\"two\"> <div开发者_如何学Python class=\"entry\">

I have the below html:


<div id="one">
    <div class="two">
        <div开发者_如何学Python class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
    </div>
</div>

in jQuery if I am to wrap every 3 elemnts in a new div like below how could I do that?


<div id="one">
    <div class="two">
        <div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
        </div>
        </div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
        </div>
        <div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
        </div>
    </div>
</div>

I tried slice and wrap which did not really help me. Any ideas? appreciate your help on this.

Thanks, L


var entries = $('#one > .two > div.entry');

entries.each(function(i) {
    if( i % 3 == 0 ) entries.slice(i,i+3).wrapAll('<div>');
});

http://jsfiddle.net/PZkSL/


Refer to this How to wrap every 3 child divs with html using jquery? or Wrap every 3 divs in a div


How about getting the div element with class "two", and iterate through it's children. When you find the first child use $(firstChild).before('<div>'); and on the third child use $(thirdChild).after('</div>'); Just iterate all the way through using this method. Haven't used .before() or .after() so not sure how this will pan out. Good luck.


I would just write a simple for loop, something like:

var two = $(".two");
var elements = $(".entry");
var group = [];
for(var i=0;i<elements.length;i++) {
  var mod = i % 3;
  if(mod == 0 && group.length > 0) {
    var container = $('<div></div>');
    two.append(container);
    for(var j=0;j<group.length;j++) {
      container[0].appendChild(group[j]);
    }
    group = [];
  }
  group[mod] = elements[i];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消