javascript 如何将多个div元素移动或复制到另一个div中?

ws51t4hk  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(247)

我想把一些html元素复制或移动到另一个div元素中。
从这里:

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

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

改为:

<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>

或者这个:

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

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

将是伟大的都知道,提前感谢!

c7rzv4ha

c7rzv4ha1#

移动: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>

副本:destination.appendChild( element.cloneNode(true) )
一个一个三个一个一个一个一个一个四个一个一个一个一个一个五个一个

rdlzhqv9

rdlzhqv92#

您可能需要使用appendTo函数(该函数添加到元素的末尾):
$("#here").appendTo("#there");
或者,您可以使用prependTo函数(添加到元素的开头):
$("#here").prependTo("#there");

相关问题