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;
添加回答
舉報