Reputation: 343
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
Reputation: 388346
Use can use
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