Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping a series of elements between two h2 tags with jquery

Tags:

jquery

I currently have a page being dynamically created like below:

<h2>a Heading</h2>
<p>a paragraph</p> 
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<h2>a Heading</h2>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  

What I'm looking to do is to use jQuery to wrap the h2 and p tags till the next h2 tag: e.g.:

<div class="headingName">
<h2>a Heading</h2>  
<p>a paragraph</p> 
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>
</div>
<div class="headingName">
<h2>a Heading</h2>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  
<p>a paragraph</p>  
</div>

So far I unsuccessfully managed this, but have gotten close using code from a user here (can't find the link to the original article):

$('.report-content h2').each(function(){
    var $set = $();
    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" />');
});

What I get is the div being wrapped around only the p tags but need to include the associated h2 tag, usually the one above the p tags.

like image 589
davidglassford Avatar asked Nov 01 '11 14:11

davidglassford


2 Answers

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
like image 50
scottheckel Avatar answered Oct 23 '22 11:10

scottheckel


$('.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/

like image 35
campino2k Avatar answered Oct 23 '22 09:10

campino2k