...">

Jquery duplicate element inside div

I have the following HTML structure:

<div id="container"> <div class='label-item-text drag' data-type='text'> <div>Right click on me and check the HTML of the duplicated</div> </div> </div> 

And I'm trying to duplicate elements inside #container . Unfortunately, it does not work as I expect.

A) My code duplicates all the elements inside, when in fact I selected only one

B) I cannot duplicate correctly

The code that duplicates all the elements is as follows.

 $('#container').append($dragRightClick.parent().html()); 

Well, parent() of $dragRightClick is #container , so I understand the reason it duplicates all elements ...

I want to duplicate only the div inside the #container , which means:

 <div class='label-item-text drag' data-type='text'> <div>Right click on me and check the HTML of the duplicated</div> </div> 

But what I still have is only:

 <div>Right click on me and check the HTML of the duplicated</div> 

The following code displays the code above:

 console.log("Clone: " + $dragRightClick.clone().html()); console.log("HTML: " + $dragRightClick.html()); 

You can check the complete problem in JSFiddle .

+5
source share
2 answers

Use outerHTML for this purpose:

Replace:

 $('#container').append($dragRightClick.parent().html()); 

from:

 $('#container').append($dragRightClick[0].outerHTML); 

UPDATED FIDDLE

You can also use this jquery plugin written for outerHTML :

http://css-tricks.com/snippets/jquery/outerhtml-jquery-plugin/

0
source

You have to use

 $('#container').append($dragRightClick.clone()); 

instead of this:

 $('#container').append($dragRightClick.parent().html()); 

See the updated JSFiddle

+1
source

Source: https://habr.com/ru/post/1203707/


All Articles