Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all div's content and append them to another div?

Tags:

jquery

append

I have 2 div's.

div1 and div2. I want to get all the content from div1 and append them to div2 and then fadeOut div1.

I tried:

$('#div1').append('#div2');
$('#div1').fadeOut();

or

$('#div1').appendTo('#div2');
    $('#div1').fadeOut();

and

$('#div1').html('#div2');
$('#div1').fadeOut();

but none seems to work for me.

What Im I doing wrong?

like image 885
jQuerybeast Avatar asked Dec 06 '22 17:12

jQuerybeast


2 Answers

The problem with .html() methods is that it converts the DOM elements to HTML and vice versa. You will loose all event handlers and data bound to those elements.

Use .contents() [docs] instead:

$("#div1").contents().appendTo('#div2').end().fadeOut();

or if you want to copy the content:

$("#div1").clone(true, true).contents().appendTo('#div2');
$("#div1").fadeOut();

It's always helpful to read the documentation when you use methods. E.g.

$('#div1').append('#div2');

will append the string #div2 to the element with ID div1. The documentation says:

Insert content, specified by the parameter, to the end of each element in the set of matched elements.

and

content: DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.

Similar for $('#div1').html('#div2');:

htmlString: A string of HTML to set as the content of each matched element.

It will just replace the content of #div1 with the string '#div2'.

On the other side

$('#div1').appendTo('#div2');

will append the element with ID div1 to the element with ID div2:

Insert every element in the set of matched elements to the end of the target.

The jQuery documentation is quite good, I recommend to read it.

like image 192
Felix Kling Avatar answered Dec 10 '22 12:12

Felix Kling


You could get the HTML of #div1 and append that to #div2:

$("#div2").append($("#div1").html());
$('#div1').fadeOut();

Here's a working example.

Notice that this is similar to your third example, which didn't work because the html method takes a string and appends it to the selected elements. In your case, it would simply append the string literal "#div2". You need to actually get the HTML you want to append from #div1, and append that.

Also note that fadeOut simply hides the element (it sets display:none), and doesn't remove it from the DOM. I'm not sure if that's what you want or not.

like image 43
James Allardice Avatar answered Dec 10 '22 12:12

James Allardice