3 回答
TA贡献1798条经验 获得超3个赞
一个简单的方法是:同时至少有一个元素在div.container移动它div.con。该元素是JavaScript的HTMLElement对象firstChild的属性,所以只要有它的第一个孩子举动div.con。
这是一个演示,其中包含大量有用的评论:
/** selecting the main "divs" and the "button" **/
let container = document.querySelector('.container'),
con = document.querySelector('.con'),
btn = document.getElementById('move');
/** click handler for the "button" **/
move.addEventListener('click', e => {
while (el = container.firstChild) con.appendChild(el); /** move the child to the other div and keep their appearnance (placement) as they were in the first "div" **/
});
/** some styling to distinguish between the two main eements (divs) **/
.container,
.con {
padding: 15px;
border: 2px solid transparent;
margin: 15px 0;
}
.container {
border-color: blue;
}
.con {
border-color: red;
}
<!-- the button is selected in "JavaScript" based on its ID (move) -->
<!-- some styling is used to distinguish between the elements : the ".contaier" has a blue border while the ".con" has a red one. Notice which element has children in it after clicking the "button" -->
<button id="move">Move elements</button>
<div class="container">
<h1>text</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="con"></div>
TA贡献1936条经验 获得超7个赞
您需要找到一种方法来从.containerdiv 中删除每个元素,然后将它们中的每一个添加到.condiv 中。我会这样做:
// get all children of container
const containerChildren = document.querySelector('.container').children;
// turn them into an array and loop through them
Array.from(containerChildren)).forEach((el) => {
// remove element
el.remove();
// select .con and add it to that div
document.querySelector('.con').append(el);
});
您可以将其转换为函数,然后将其添加到按钮中,如下所示:
function handleClick() {
const containerChildren = document.querySelector('.container').children;
Array.from(containerChildren)).forEach((el) => {
el.remove();
document.querySelector('.con').append(el);
});
}
document.querySelector('button').onclick = handleClick;
添加回答
举报
