Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery complete the tags on its own

Tags:

jquery

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.

like image 630
Mukund Zare Avatar asked Jan 16 '23 19:01

Mukund Zare


2 Answers

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>');
like image 142
João Silva Avatar answered Jan 30 '23 04:01

João Silva


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.


My answer has one downvote from an anonymous downvoter, surely because I had used $('.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> 
like image 37
undefined Avatar answered Jan 30 '23 04:01

undefined