【问题标题】:jQuery to iterate over every childNodes of bodyjQuery遍历body的每个childNodes
【发布时间】:2015-02-24 17:03:48
【问题描述】:

目标:我想迭代并打印出 html 正文的每个 childNodes,我使用了 document.body.childNodes 方法。到目前为止,它还没有打印出身体的每个子节点。这是我的代码

<body>
    <p><div class="zero"><div class="one"><span class="two">hello</span></div></div></p>
</body>

这是我的 jQuery 脚本:

$(document).ready(function(){
    console.log(document.body.childNodes);
});

我的结果是: [text, p, div.zero, p, text, item: function]

div class="one", span class="two" 去哪里了?我可以做些什么来遍历 body 的所有 childNode?​​p>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你只看到第一级孩子的问题。

    要遍历所有可以使用 jquery 的东西!

    $("body").find("*").each(function(){
      var currentElement = $(this); //jquery object
      var currentElementNotJquery = this; //html element
      //some code here
    });
    

    或者通过编写递归过程:

    类似的东西:

    function iterate(node){
      if(node.firstChild)
        for(var i in node.childNodes)
          iterate(node.childNodes[i]);
      console.log(node);
    }
    

    然后运行它们:iterate(document.body)

    【讨论】:

      【解决方案2】:

      看一下jquery函数: .each()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-09
        • 1970-01-01
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 2021-03-19
        • 2011-10-05
        • 2016-09-17
        相关资源
        最近更新 更多