展平嵌套的HTML DOM节点

时间:2018-04-22 15:51:21

标签: javascript html dom

给出一个像这样的HTML片段:

<div>
  <div>
    <h2>Hello</h2>
    <p>Hello world</p>
  </div>
  <h3>Hello 2</h3>
</div>

我想将此“扁平化”为:

<div></div>
<div></div>
<h2>Hello</h2>
<p>Hello world</p>
<h3>Hello 2</h3>

我怎么能用Javascript / jQuery做到这一点?

2 个答案:

答案 0 :(得分:1)

for (var i = 0; i < document.body.children.length; i++) {
    var e = document.body.children[i];
    for (var child of e.children) {
        document.body.appendChild(child);
    }

}

因为document.body.children是一个“实时”集合,所以当您将项目附加到正文时它会发生变化,因此您的正文本身将作为要在横向遍历中处理的元素的队列。

(我正在混合循环类型,因为我不是100%确定迭代器与实时集合的工作方式相同,而且我不在计算机上检查。如果我或某人可以确认for (var e of document.body.children)以同样的方式工作,我将更新解决方案。)

答案 1 :(得分:0)

使用“实时选择器” document.body.children

以下是ES6代码段

for (const e of document.body.children) {
    for (const child of e.children) {
        document.body.appendChild(child);
    }
}
相关问题