0

I have two divs as follows:

<div id='div1'>
    <p>Hello world!</p>
</div>

<div id='div2'>

</div>

<a id='test' href='javascript:void()'>Click me to fill in div2</a>

I have been wondering what should be the best way to fill in div2 with the content of div1 onclick using jquery in order to have

<div id='div1'>
        <p>Hello world!</p>
    </div>
user908715
  • 29
  • 1
  • 4

3 Answers3

5

Append a clone of the contents of $("#div1") to $("#div2") using .contents(), .clone(), and .append():

$("#div2").append($("#div1").contents().clone());
gilly3
  • 87,962
  • 25
  • 144
  • 176
2

Rather than resorting to serialising to HTML and then applying that to the other element, as Andy's answer does, it would be nicer to clone the nodes.

$('#test').click(function(e) {
    e.preventDefault();
    $('#div1').contents().clone(true).appendTo('#div2');
});

This has the advantage that any data or events on the elements cloned will continue to exist on the new elements. Since I've used e.preventDefault(), you can also lose the javascript:void bit of your code, because the link's default action has been prevented.

See the jQuery API:

Community
  • 1
  • 1
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
1
$('#div2').html($('#div1').html());
Andy
  • 29,707
  • 9
  • 41
  • 58