user3581244
user3581244

Reputation: 547

jQuery select groups of tags

Say I had this structure:

<p>Some text random 1</p>
<p>Some text random 2</p>
<p>Some text random 3</p>
<div><img src=""></div>
<p>Some text random 4</p>
<p>Some text random 5</p>

I want to surround groups of p tags in a div element, does anyone know of the best way to go about this. The preferred output would be:

<div class="p-tags">
    <p>Some text random 1</p>
    <p>Some text random 2</p>
    <p>Some text random 3</p>
</div>
<div><img src=""></div>
<div class="p-tags">
    <p>Some text random 4</p>
    <p>Some text random 5</p>
</div>

Upvotes: 1

Views: 53

Answers (2)

Shivam Chopra
Shivam Chopra

Reputation: 639

To Wrap all the elements in one, you can use wrapAll

To Find element above image and below image, you can use prevAlland nextAll respectively.

$('button').on('click', function(){
    $('img').parents('div').prevAll().wrapAll('<div class="p-tags"></div>');
$('img').parents('div').nextAll().wrapAll('<div class="p-tags"></div>');
});

Demo

Upvotes: 2

ozil
ozil

Reputation: 7117

you can use wrapAll

$("p").slice(0,3).wrapAll('<div class="p-tags"></div>');
$("p").slice(3,5).wrapAll('<div class="p-tags"></div>');  

DEMO

Upvotes: 2

Related Questions