2015-02-24 76 views
1

目标:我想迭代并打印出html body的每个childNodes,并使用document.body.childNodes方法。到目前为止,它并没有打印出身体的每个子节点。这里是我的代码jQuery遍历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); 
}); 

我的结果是: [文字,P,div.zero,P,文字资料:功能]

在哪里div class =“one”,span class =“two”go?我可以做什么来遍历body的所有childNode?

回答

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); 
} 

并运行它们:迭代(document.body的)