Why jQuery fully executes tags

I am trying to encapsulate a tag with other div tags of classes A and B. This is what my last result should look like:

<div class="A"> <div class="B"> **<div class="C"></div>** </div> </div> 

For this, I use the following code:

 <script> jQuery('<div class="A"><div class="B">').insertBefore('.C'); jQuery('</div></div>').insertAfter('.C'); </script> 

However, the code is output as:

 <div class="A"> <div class="B"> </div> </div> <div class="C"> </div> 

This is clearly not what I intended. Please, help.

+4
source share
4 answers

wrap is a necessary function, 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>'); 
+4
source

You can use the wrap() method:

Wrap the 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 downstream signal from an anonymous downvoter, of course, because I used $('.C').wrap('<div class="A"/>') , and the commentator also said that it is broken. Here is the jQuery documention part:

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 internal <div> elements, for example:

 $('.inner').wrap('<div class="new" />'); 

A 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> 
+3
source

your calls are wrong

it should be

 <div class="C">Some Text</div> <script type="text/javascript"> $(function(){ $(".C").wrap($("<div class='A' />")).wrap($("<div class='B' />"));​ }); </script> 

You did not close the div class in the first call, so you left jquery to handle it, as developers implement the innsertAfter method.

Working example http://jsfiddle.net/mjaric/kZSTu/1

+2
source

Perhaps this is not jQuery, but the browser that runs it. I saw the Chrome inspector output end tags, where I forgot them in the original markup.

It sounds like you really want to use the wrap() function.

Your script will look like this:

 $('.C').wrap(function () { return '<div class="A"><div class="B">'; }); 
0
source

All Articles