codek
codek

Reputation: 343

Wrap generated tags on separated divs

I have this markup generated and I can´t modify it:

<h2>Title</h2>
<p>text</p>
<p>text</p>
<p>text</p>
<h3>Title</h3>
<p>text</p>
<p>text</p>
<p>text</p>
    <p>text</p>
    <p>text</p>
<h3>Title</h3>
<p>text</p>
<p>text</p>

What I want is to wrap it like this using jQuery:

<div class="article">
    <h2>Title</h2>
    <p>text</p>
    <p>text</p>
    <p>text</p>
</div>
<div class="article">
    <h3>Title</h3>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
</div>
<div class="article">
    <h3>Title</h3>
    <p>text</p>
    <p>text</p>
</div>

Any ideas how do to do it? As you can see the number of p tags vary so I don´t know how to target this.

Upvotes: 2

Views: 60

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388346

Use can use

  • header-selector - to select the header elements
  • nextUntil() - to select all the other sibling elements under the article
  • addBack() - add the header element back to the element set
  • wrapAll() - wrap all elements with the div

Try

$(':header').each(function(){
    $(this).nextUntil(':header').addBack().wrapAll('<div class="article" />')
})

Demo: Fiddle


A slightly better performing version can be(since it can make use of css selectors)

$('h2, h3').each(function () {
    $(this).nextUntil('h2, h3').addBack().wrapAll('<div class="article" />')
})

Demo: Fiddle

Upvotes: 7

Related Questions