Wrapping a series of elements between two h2 tags with jquery

$('.report-content h2').each(function(){
    var $set = $(this); // this is your key ;)
    var nxt = this.nextSibling;
    while(nxt) {
        if(!$(nxt).is('.report-content h2')) {
            $set.push(nxt);
            nxt = nxt.nextSibling;
        } else break;
    } 
   $set.wrapAll('<div class="content" />');
});

See http://jsfiddle.net/mMpVB/


P.S. If anyone is looking for the answer to this for jQuery 1.8+, addSelf() is deprecated in favor of addBack().

A modification to @Hexxagonal's answer worked for me:

$('.report-content h2').each(function(){ 
    var $set = $(this).nextUntil("h2").addBack();
    $set.wrapAll('<div class="content" />');
});

See:

  • https://api.jquery.com/andself/
  • https://api.jquery.com/addBack/

Take each h2, grab all sibilings until you get another h2 (or there are no elements at this level) and then reinclude the h2 in the set. Here's the JSFiddle.

$('.report-content h2').each(function(){ 
    $(this)
        .nextUntil("h2")
        .addBack()
        .wrapAll('<div class="content" />');
});

jQuery Documentation

  • nextUntil
  • addBack
  • wrapAll

Tags:

Jquery