5

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 the items inside #container. Unfortunately is not working as I expect.

A) My code duplicates all the items inside, when actually I have only selected one

B) I can't duplicate properly

The code that duplicates all items is the following.

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

Well, the parent() of $dragRightClick is the #container, so I understand the reason why it duplicate all the items...

What I want to duplicate is only the div inside the #container, that 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've got so far is only:

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

The following code outputs the above code:

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

You can check the full problem in JSFiddle.

Community
  • 1
  • 1
Linesofcode
  • 5,327
  • 13
  • 62
  • 116

2 Answers2

1

You should use

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

instead of this :

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

See updated JSFiddle

laruiss
  • 3,780
  • 1
  • 18
  • 29
0

Use outerHTML for this purpose:

Replace:

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

with:

$('#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/

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Well, I've heard about outerHTML and it started working on firefox 11..http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html - But maybe, that's not a big problem in nowadays? – Linesofcode Sep 30 '14 at 11:37
  • `outerHTML` is javascript property of element – Ehsan Sajjad Sep 30 '14 at 11:40