简体   繁体   中英

jQuery wrap 2 div objects inside new div

I have 2 div objects. How can I wrap those inside another div? I cannot just use $('.one, .two, .three').wrapAll('<div class="wrap">') because all the small boxes are dynamic and there can be multiple of those. I want to wrap just 2 of them in one.

HTML:

<div class="grid">
    <div class="grid-item item1"></div>
    <div class="grid-item item2 small-box"></div>
    <div class="grid-item item3 small-box"></div>
    <div class="grid-item item4"></div>
    <div class="grid-item item2 small-box"></div>
    <div class="grid-item item3 small-box"></div>
</div>

jQuery:

function small_box_modify(){
    var $box = $('.grid > .grid-item');
    var $small_box = $('.grid > .small-box');
    $small_box.each(function (index) {
        var $this = $(this);
        if( $this.hasClass('small-box') ){
            var $nxt = $this.next('.grid-item');
            if( $nxt.hasClass('small-box') ){
                // here I want to wrap "$this" and "$nxt" inside new div
                // $($this, $nxt).wrapAll('<div class="wrapper">');
            }
        }
    });
}

RESULT HTML:

<div class="grid">
    <div class="grid-item item1"></div>
    <div class="wrapper">
        <div class="grid-item item2 small-box"></div>
        <div class="grid-item item3 small-box"></div>
    </div>
    <div class="grid-item item4"></div>
    <div class="wrapper">
        <div class="grid-item item2 small-box"></div>
        <div class="grid-item item3 small-box"></div>
    </div>
</div>

You may use like this:

if( $nxt.hasClass('small-box') ){
  // here I want to wrap "$this" and "$nxt" inside new div
  for(var i = 0; i < $nxt.length; i+=2) {
    $($this).add($nxt).wrapAll("<div class='wrapper' />");
  }
}

You can also do it like this :

var $set = $('div.grid > .small-box');   
for(var i=0, len = $set.length; i < len; i+=2){
    $set.slice(i, i+2).wrapAll('<div class="wrapper"/>');
}   

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