I have this HTML:
<div id="description">
<h5>Title</h5>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
</div>
I want to insert, with jQuery, a parent element for all <p>
elements, except the first one. So the HTML that I would like to generate is this:
<div id="description">
<h5>Title</h5>
<p>First paragraph</p>
<div class="details">
<p>Second paragraph</p>
<p>Third paragraph</p>
</div>
</div>
There's the .wrap()
function in jQuery that can add a parent, but if I use it like this:
$("#description p:not(:first)").wrap('<div class="details" />');
It wraps all my <p>
individually.
Is there any way I can modify my selector to put my <div>
around the "group" instead? Or maybe it's easier using a different function that is yet unknown to me?
Thanks!
The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.
To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.
So you are looking for the .wrapAll()
method.
$("#description p").not(":first").wrapAll('<div class="details" />');
Ref.: .wrapAll()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With