3

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!

venndi
  • 161
  • 9
  • 4
    There's a few ways, but effectively you move multiple elements the same way you move *one* element, but that moving action is repeated. Have you made any attempts? Where did you get stuck? – David Thomas Jan 27 '23 at 18:15
  • Does this answer your question? [How to move all HTML element children to another parent using JavaScript?](https://stackoverflow.com/questions/20910147/how-to-move-all-html-element-children-to-another-parent-using-javascript) – disinfor Jan 27 '23 at 18:15

2 Answers2

2

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>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
0

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");

K_arma9
  • 1
  • 1