jquery insert a html block so it starts before the target and ends after the target - is this possible?

StackOverflow https://stackoverflow.com/questions/3044213

  •  27-09-2019
  •  | 
  •  

Question

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

Was it helpful?

Solution

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>

OTHER TIPS

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top