Home > Enterprise >  How to move or copy more than one div element into another div?
How to move or copy more than one div element into another div?

Time:01-28

I want to copy or move some html elements into another div element.

From this:

<ul class='here'>
<li>text1</li>
<li>text2</li>
<li>text3</li>
</ul>

<ul class='there'>
</ul>

to this:

<ul class='here'>
<li>text1</li>
<li>text2</li>
<li>text3</li>
</ul>

<ul class='there'>
<li>text1</li>
<li>text2</li>
<li>text3</li>
</ul>

or to this:

<ul class='here'>
</ul>

<ul class='there'>
<li>text1</li>
<li>text2</li>
<li>text3</li>
</ul>

Would be great both to know, thanks in advance!

CodePudding user response:

You may want to use the appendTo function (which adds to the end of the element):

$("#here").appendTo("#there");

Alternatively, you could use the prependTo function (which adds to the beginning of the element):

$("#here").prependTo("#there");

CodePudding user response:

move: destination.appendChild( element )

const destination = document.querySelector('ul.there');

document.querySelectorAll('ul.here > li')
  .forEach( elm => destination.appendChild(elm) );
ul { width: 5em;height: 6em;border: 1px solid orange;display: inline-block;margin: 0 1em;padding-top: .5em;vertical-align: text-top;padding: 0;list-style: none; }
ul:before { display: block;content: '_' attr(class);color: green;border-bottom: 1px solid orange;margin-bottom: .3em; }
li { padding-left: 1em; }
<ul class='here'>
  <li>text1</li>
  <li>text2</li>
  <li>text3</li>
</ul>

<ul class='there'>
</ul>

copy: destination.appendChild( element.cloneNode(true) )

const destination = document.querySelector('ul.there');

document.querySelectorAll('ul.here > li')
  .forEach( elm => destination.appendChild(elm.cloneNode(true)) );
ul { width: 5em;height: 6em;border: 1px solid orange;display: inline-block;margin: 0 1em;padding-top: .5em;vertical-align: text-top;padding: 0;list-style: none; }
ul:before { display: block;content: '_' attr(class);color: green;border-bottom: 1px solid orange;margin-bottom: .3em; }
li { padding-left: 1em; }
<ul class='here'>
  <li>text1</li>
  <li>text2</li>
  <li>text3</li>
</ul>

<ul class='there'>
</ul>

  • Related