[英]Move HTML children elements out of parent and remove the parent element
Trying to move children outside of parent then remove the parent itself in vanilla JavaScript.尝试将子级移出父级,然后在 vanilla JavaScript 中删除父级本身。 Current code looks something like this:当前代码如下所示:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
Desired output:期望的输出:
<div class="child"></div>
<div class="child"></div>
Try setting outerHTML
property to innerHTML
property.尝试将outerHTML
属性设置为innerHTML
属性。
const parent = document.querySelector('.parent')
parent.outerHTML = parent.innerHTML
See live demo:看现场演示:
console.log('Before change: ', document.querySelector('.container').innerHTML) const parent = document.querySelector('.parent') parent.outerHTML = parent.innerHTML console.log('After change: ', document.querySelector('.container').innerHTML)
<div class="container"> <div class="parent"> <div class="child"></div> <div class="child"></div> </div> </div>
You can do it as in the @MichałPerłakowski answer using . outerHTML
您可以按照@MichałPerłakowski 的回答使用. outerHTML
. outerHTML
and . innerHTML
. outerHTML
和. innerHTML
. innerHTML
, which is ok if you are not critical about speed (parsing HTML into DOM nodes) and do not care about attached event listeners, etc. . innerHTML
,如果您对速度(将 HTML 解析为 DOM 节点)不挑剔并且不关心附加的事件侦听器等,则可以。
More efficient and resilient solution would be by juggling with dom elements:更有效和更有弹性的解决方案是使用 dom 元素:
while(parentElement.childNodes.length){
parentElement.before(parentElement.childNodes[0]);
}
parentElement.remove();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.