3 回答
TA贡献1836条经验 获得超4个赞
一种方法是简单地更换parentNode的innerHTMLs的在.components-drop-area innerHTMLS:
let dropAreas = document.querySelectorAll('.components-drop-area');
for (let i = 0; i < dropAreas.length; i++) {
dropAreas[i].parentNode.innerHTML = dropAreas[i].innerHTML;
}
// The <div> contents have now been extracted, and the <div> elements removed
console.log(document.querySelector('table').innerHTML);
<table>
<tbody>
<tr>
<th>
<div class="components-drop-area">
<p>aa</p>
<p>bb</p>
</div>
</th>
</tr>
<tr>
<th>
<div class="components-drop-area">
<p>cc</p>
<p>dd</p>
</div>
</th>
</tr>
</tbody>
</table>
TA贡献1842条经验 获得超21个赞
如果要使用 vanilla DOM 操作,则必须从选定的 div 元素中获取每个子元素,并将它们插入到该节点的父元素中,使用选定的 div 本身作为参考,然后再将其删除。每个 DOM 节点都有对其父节点和子节点的引用,因此您可以执行与每个选定节点相关的所有操作,如下所示:
for (const node of document.querySelectorAll("table .components-drop-area")) {
const parent = node.parentNode;
const children = Array.from(node.children);
for (const child of children) {
node.removeChild(child);
parent.insertBefore(child, node);
}
parent.removeChild(node);
}
TA贡献1804条经验 获得超7个赞
这是对 James 的 vanilla JS 实现的改编,应该可以工作
for (const node of document.querySelectorAll("table .components-drop-area")) {
const parent = node.parentNode;
while (node.children.length>0) {
let child = node.children[0];
node.removeChild(child);
parent.insertBefore(child, node);
}
parent.removeChild(node);
}
循环遍历元素很棘手,因为我们在迭代期间修改了集合
for (const node of document.querySelectorAll("table .components-drop-area")) {
const parent = node.parentNode;
while (node.children.length>0) {
let child = node.children[0];
node.removeChild(child);
parent.insertBefore(child, node);
}
parent.removeChild(node);
}
// The <div> contents have now been extracted, and the <div> elements removed
console.log(document.querySelector('table').innerHTML);
<table>
<tbody>
<tr>
<th>
<div class="components-drop-area">
<p>aa</p>
<p>bb</p>
</div>
</th>
</tr>
<tr>
<th>
<div class="components-drop-area">
<p>cc</p>
<p>dd</p>
</div>
</th>
</tr>
</tbody>
</table>
添加回答
举报