views:

82

answers:

2

Hi all,

I understand you can add insert blocks of html before and after a target using before(), insertBefore(), after() and insertAfter().

I tried to do something similar to this

<script type="text/javascript">
    $(document).ready(function(){
        $("p").before("<div class='myContainer'>");
        $("p").after("</div>");
    });
</script>

<p>paragraph</p>

But the inject seems to automatically create closing tags for me, is there a way around this?

Cheers

+4  A: 

There's a function for that :) Use .wrap(), like this:

$("p").wrap("<div class='myContainer'>");

This will wrap each <p> independent, you can see a demo here, it changes this:

<p>Paragraph 1</p>
<p>Paragraph 2</p>​

Into this:

<div class='myContainer'>
  <p>Paragraph 1</p>
</div>
<div class='myContainer'>
  <p>Paragraph 2</p>​
</div>
Nick Craver
"There's a function for that".. nice slogan for jQuery :)
Anurag
Perfect! Thank you, and yes nice slogan hehe
Chris
A: 

Just to mention you could also do:

$myDiv = $("<div class='myContainer'></div>");
$("p").wrap($myDiv);

and then again at a later time append stuff to myDiv with

$myDiv.append("This is going to be the text in myContainer");
Ain
He wants to wrap the `<div>` around the `<p>` though, this would result in `<p>Something</p><div class='myContainer'></div>`.
Nick Craver
@Nick thanks, just corrected my answer!
Ain