HTML DOM
<div class="box-1">
...
</div>
<div class="box-2">
...
</div>我可以使用JavaScript删除</div><div class="box-2">的这一部分吗?
任何帮助,谢谢提前!
发布于 2020-04-30 08:06:36
使用DOM方法,一个简化的例子可以是:
// ref .box-1 and .box-2
const box1 = document.querySelector('.box-1');
const box2 = document.querySelector('.box-2');
// move all child nodes from box2 to box1
// Array.from (or any method to copy a *live* DOM NodeList) is needed,
// for otherwise the DOM manipulation would throw off the loop
Array.from(box2.childNodes).forEach(child => box1.appendChild(child));
// afterwards, remove box2
box2.parentNode.removeChild(box2);<div class="box-1">
<span>A</span>
B
</div>
<div class="box-2">
<span>C</span>
D
</div>
另一种选择是在某些元素的innerHTML上使用字符串操作,但这种操作很快就会变得混乱,所以我不推荐它。
发布于 2020-04-30 07:59:29
如果我没有错,你想把下一个兄弟姐妹的孩子加到前一个,然后去掉前一个兄弟姐妹的孩子。在这种情况下,请考虑以下输入:
<div class="box-1">
SomeText
<div>child</div>
</div>
<div class="box-2">
Some other text
<div>other child</div>
</div>您可以编写此函数或类似的内容:
function transfer(node){
var next = node.nextElementSibling;
if(!next){return};
while(next.hasChildNodes()){
node.appendChild(next.firstChild)
}
next.parentNode.removeChild(next);
}
transfer(body.querySelector("div"));你会得到:
<div class="box-1">
SomeText
<div>child</div>
Some other text
<div>other child</div>
</div>发布于 2020-04-30 07:52:24
我觉得很管用
var elmnt1 = document.getElementsByClassName("box-1")[0];
var elmnt2 = document.getElementsByClassName("box-2")[0];
elmnt1.appendchild(elmnt2);
elmnt2.remove();https://stackoverflow.com/questions/61518326
复制相似问题