How can I get all the contents of a div and add them to another div?

I have 2 divs.

div1 and div2. I want to get all the content from div1 and add it 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 no one works for me.

What am I doing wrong?

+4
source share
5 answers

The problem with .html() methods is that it converts DOM elements to HTML and vice versa. You will lose all event handlers and data associated with these elements.

Use .contents() [docs] :

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

or if you want to copy the contents:

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

It is always useful to read documentation when using methods. For instance.

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

will add the line #div2 to the element with the identifier div1 . The documentation states:

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

and

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

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

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

It will simply replace the contents of #div1 with the string '#div2' .

On the other hand

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

will add an element with identifier div1 to an element with identifier div2 :

Insert each element into the set of matched elements at the end of the target.

The jQuery documentation is pretty good, I recommend reading it.

+8
source

You can get HTML #div1 and add it to #div2 :

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

Here is a working example .

Note that this is similar to your third example, which does not work, because the html method takes a string and adds it to the selected elements. In your case, it will just add the string literal "# div2". You need to get the HTML code you want to add from #div1 and add it.

Also note that fadeOut just hides the element (it sets display:none ) and does not remove it from the DOM. I'm not sure if you want it or not.

+7
source
 $('#div2').html($('#div2').html()); 

must work.

0
source

This is a small example of how you put this text below in HTML format.

 <div id="div1"> <p>hi</p> </div> <div id="div2"></div> 

and below script

 $("#div2").append($("#div1").html()); $('#div1').fadeOut(); 
0
source
 content = $('#div1').html(); $('#div2').append(content); $('#div1').fadeOut(); 
0
source

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


All Articles