128

Need some jquery help copying a DIV into another DIV and hoping that this is possible. I have the following HTML:

  <div class="container">
  <div class="button"></div>
  </div>

And then I have another DIV in another location in my page and I would like to copy the 'button' div into the following 'package' div:

<div class="package">

Place 'button' div in here

</div>
Dan
  • 1,709
  • 5
  • 15
  • 21

4 Answers4

202

You'll want to use the clone() method in order to get a deep copy of the element:

$(function(){
  var $button = $('.button').clone();
  $('.package').html($button);
});

Full demo: http://jsfiddle.net/3rXjx/

From the jQuery docs:

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page.

chrx
  • 3,524
  • 1
  • 15
  • 17
  • 1
    This does not keep values added by the user on inputs. – wtf8_decode Jan 13 '15 at 14:28
  • 8
    can you please tell me why we need `$` in `var $button`. I believe in js you can declare var simply as `var button` . – KNU Nov 06 '15 at 07:16
  • 29
    @KNU It's not necessary but it's a common convention in the jQuery world. It indicates that the $button variable is a jQuery object. See http://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign – chrx Nov 07 '15 at 21:20
  • You are using a jQuery object as input argument to the html method. Reading jQuery's documentation of html(), that method takes either nothing, a HTML string or a function as input. Please explain why your solution works. Thanks! – Goran W Mar 09 '23 at 00:30
26

Copy code using clone and appendTo function :

Here is also working example jsfiddle

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="copy"><a href="http://brightwaay.com">Here</a> </div>
<br/>
<div id="copied"></div>
<script type="text/javascript">
    $(function(){
        $('#copy').clone().appendTo('#copied');
    });
</script>
</body>
</html>
Sunny S.M
  • 5,768
  • 1
  • 38
  • 38
4

You can copy your div like this

$(".package").html($(".button").html())
JAVAGeek
  • 2,674
  • 8
  • 32
  • 52
2

Put this on an event

$(function(){
    $('.package').click(function(){
       var content = $('.container').html();
       $(this).html(content);
    });
});
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103