Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a parent element to a group of paragraph?

Tags:

jquery

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!

like image 751
Gabriel Avatar asked Aug 22 '10 18:08

Gabriel


People also ask

How do you target a parent element in CSS?

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.

How do you get a div as a parent?

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.


1 Answers

So you are looking for the .wrapAll() method.

$("#description p").not(":first").wrapAll('<div class="details" />');

Ref.: .wrapAll()

like image 199
jAndy Avatar answered Nov 15 '22 05:11

jAndy