javascript - 按顺序遍历 DOM 叶子

标签 javascript html dom

我正在寻找遍历特定元素的叶子的最有效方法。例如:

<div id='root'>
  <ul>
    <li>One</li>
    <li>Two</li>
  </ul>
  <div>
    <p>Paragraph</p>
    <div>
      <b>
        <i>Text</i>
      </b>
      <u>Underline</u>
    </div>
  </div>
</div>

我应该得到一个数组:[<li>One</li>, <li>Two</li>, <p>Paragraph</p>, <i>Text</i>, <u>Underline</u>] 。理想情况下应该是这个顺序。

最佳答案

简单的“旧”Javascript

(function() {
    var nodes = document.querySelectorAll("#root *"),
        result;

    result = [].slice.apply(nodes).filter(function(i) {
        return i.childNodes.length === 1 && i.firstChild.nodeType === 3;
    })

    console.log(result);
}())​

example

关于javascript - 按顺序遍历 DOM 叶子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11975369/

相关文章:

html - 设置网格样式结果的问题

javascript - 我可以在 CSS 属性中使用全局变量吗

javascript - 使用 Jquery 获取和设置内容的位置

javascript - 根据显示/隐藏 CSS 调整列宽

javascript - 如何禁用 Webview 滚动并设置其高度以适合整个内容

html - 在我的网站 html 上使用 2 个样式表

html - 列表项的图像在 html 中重复

javascript - Rally 类 xtype 值在哪里分配

dom - 如何读取加载了来自另一个域的页面的 iframe 的 DOM?

javascript - react : How to read from the DOM after mount?