WrapAll jQuery problem

I need to wrap three divs in one, but this group of three divs is repeated multiple times in the code. Maybe my HTML will explain:

<div class="one" />
<div class="two" />
<div class="three" />

<div class="one" />
<div class="two" />
<div class="three" />

      

I am trying to achieve this:

<div class="wrap">
  <div class="one" />
  <div class="two" />
  <div class="three" />
</div>

<div class="wrap">
  <div class="one" />
  <div class="two" />
  <div class="three" />
</div>

      

This wraps everything in one div:

$('.one, .two, .three').wrapAll('<div class="wrap" />')

      

How can I gather groups separately?

+2


source to share


5 answers


$(function(){
    var all = $('.one, .two, .three');
    for(i=0; i<all.length; i+=3){
        all.slice(i,i+3).wrapAll('<div class="wrap" />');
    }
});

      

See it in action: http://jsbin.com/uqosa/



By the way, <div class="one" />

didn't work for me in Firefox, I had to close them with </div>

.

+5


source


Try the following:



$('div.one').each(function() {
    var wrap = $(this).wrap('<div class="wrap"></div>').parent();
    wrap.next('div.two').appendTo(wrap);
    wrap.next('div.three').appendTo(wrap);
});

      

+1


source


This will work:

$(function() {
    var $ones = $('div.one');
    var $twos = $('div.two');
    var $threes = $('div.three');

    $ones.each(function(idx) {
        $('<div class="wrap"></div>')
            .append($ones.eq(idx))
            .append($twos.eq(idx))
            .append($threes.eq(idx))
            .appendTo('body');
    });
});

      

+1


source


In my head, this should work:

$('.one').each(function() {
    var wrap = $('<div>').addClass('wrap'), two = $(this).next(), three = $(two).next();
    $(this).after(wrap).appendTo(wrap)
    two.appendTo(wrap), three.appendTo(wrap)
});

      

0


source


$.fn.matchUntil = function(expr) {
    var match = [];
    this.each(function(){
        match = [this];
        for ( var i = this.nextSibling; i; i = i.nextSibling ) {
            if ( i.nodeType != 1 ) { continue; }
            if ( $(i).filter(expr).length > 0 ) { break; }
            match.push( i );
        }
    });
    return this.pushStack( match );
};

      

using:

$(".one").each( function() {
    $(this).matchUntil(".one").wrapAll("<div class='wr'></div>");
})

      

this is just a modified version of http://docs.jquery.com/JQuery_1.2_Roadmap#.nextUntil.28.29_.2F_.prevUntil.28.29 which doesn't seem to work with the new jQuery.

0


source







All Articles