tags:

views:

22

answers:

1

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!

+8  A: 

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

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

Ref.: .wrapAll()

jAndy
Nice! Clean and easy solution! Thank you jAndy! One subquestion: is there a reason why you wrote the selector using .not() instead of :not? (I learn jQuery by myself so if there's a subtlety there, I don't know about it.) Thanks again!
Gabriel
@Gabriel: It is in general faster to use methods for reducing a "wrapped set" of nodes. By using the `:not()` notation, `Sizzle` (John Resigs css query engine) has to do the job. And that on the other hand, is slower in most situations.
jAndy