I am trying to encapsulate the tag with the other div tags with classes A and B. Here's what my final result should look like:
<div class="A">
<div class="B">
**<div class="C"></div>**
</div>
</div>
I am using the following code to do it:
<script>
jQuery('<div class="A"><div class="B">').insertBefore('.C');
jQuery('</div></div>').insertAfter('.C');
</script>
However, the code comes out as:
<div class="A">
<div class="B">
</div>
</div>
<div class="C">
</div>
This is clearly not what I intended. Please help.
wrap
is the function you need, since you want to wrap two div
tags around an existing one, instead of inserting new tags before or after it:
$('.C').wrap('<div class="A"><div class="B"></div></div>');
You can use the wrap()
method:
Wrap an HTML structure around each element in the set of matched elements.
$('.C').wrap('<div class="A"><div class="B"></div></div>');
Fiddle
Note that jQuery('</div></div>').insertAfter('.C');
does not generate html tags.
$('.C').wrap('<div class="A"/>')
and a commenter also said that it's broken. Here is the part of jQuery documention
:
Consider the following HTML:
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
Using .wrap()
, we can insert an HTML structure around the inner <div>
elements like so:
$('.inner').wrap('<div class="new" />');
The new <div>
element is created on the fly and added to the DOM. The result is a new <div>
wrapped around each matched element:
<div class="container">
<div class="new">
<div class="inner">Hello</div>
</div>
<div class="new">
<div class="inner">Goodbye</div>
</div>
</div>
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