user995317
user995317

Reputation: 355

Wrap all tags between h2 and image tag

I have page where is normal article content. I would need to wrap some of the tags into div. I can do it with wrap() but how I'm able to select all tags between I'm not sure. Do I have to use regex? I'm terrible with that.

So basically right now the markup is:

    <h1>Title</<h1>
    <p>Text....</p>
    <p>Text....</p>

    <h2>Title 2</h2>
    <p>Text....</p>
    <ul><li>List Text....</li</ul>
    <p>Text....</p>
    <img src="" />

    <h2>Title</<h2>
    <p>Text....</p>
<img src="" />
    <p>Text....</p>

And this is what I would hope it to be:

    <h1>Title</<h1>
    <div class="wrap">
        <p>Text....</p>
        <p>Text....</p>
    </div>

        <h2>Title 2</h2>
    <div class="wrap">
        <p>Text....</p>
        <ul><li>List Text....</li</ul>
        <p>Text....</p>
    </div>
        <img src="" />

        <h2>Title</<h2>
    <div class="wrap">
        <p>Text....</p>
</div>
<img src="">
<div class="wrap">
        <p>Text....</p>
    </div>

Meaning that all tags between and another or should be wrapped in div. Is this possible even? Cheers!

EDIT: my markup wasn't correct first time, so i changed it a bit.

Upvotes: 1

Views: 181

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388446

You can use nextUntil()

$('h2').each(function(){
    $(this).nextUntil('h2, img').wrapAll('<div class="wrap">')
})

Demo: Fiddle

Upvotes: 1

Related Questions