DOM使用jquery逐个遍历节点

pra*_*vin 5 html javascript jquery dom

我想通过维护序列在网页上逐节点遍历.

以下是基本DOM:

<BODY>
     <DIV id ='1'> Test 1 </DIV>
     <DIV id='2'> Details about <SPAN id='3'> Execution </SPAN> </DIV>   
</BODY>
Run Code Online (Sandbox Code Playgroud)

按照上面的例子,我想逐个节点遍历每个节点

1st Traversal : <BODY>

2nd Traversal : <DIV id ='1'>

3rd Traversal : <DIV id='2'>

4rd Traversal : <SPAN id='3'>
Run Code Online (Sandbox Code Playgroud)

我的动机是遍历当前页面上可用的所有节点,并逐个访问每个节点,简单地说是nextnode(),而不是查看父和子关系.Exepcted是,它应该按照以下顺序访问每个节点.

所以我的发言是这样的:

startnode //consider this is start node

While ( startnode!=null ) {

  // will process on startnode

   startnode= startnode->nextnode();
  // something like that to visit each node
}
Run Code Online (Sandbox Code Playgroud)

有谁知道这个,如何使用jquery(最好)或javascript实现这一点,请分享他们的参考.

谢谢

-Pravin

use*_*716 14

总是有标准的Crockford 走dom方法.

示例: http ://jsfiddle.net/FJeaY/

var walk_the_DOM = function walk(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walk(node, func);
        node = node.nextSibling;
    }
};

walk_the_DOM(document.body, function(node) {
    if(node.nodeType == 1)
        alert(node.id);  // alert if we have a type 1 node
})?;?
Run Code Online (Sandbox Code Playgroud)

walk_the_DOM从这里复制的具体代码示例: http ://snipplr.com/view/19815/walking-the-dom/

编辑:文本节点具有nodeType = 3,因此您可以将其添加到您的if()语句中,如果需要的话.

walk_the_DOM(document.body, function(node) {
    if(node.nodeType == 1 || node.nodeType == 3)
        alert(node.id);  // ID will be undefined if it is a text node
})?;?
Run Code Online (Sandbox Code Playgroud)


Nic*_*ver 12

您可以使用正文和所有选择器进行循环,如下所示:

$("body").find("*").andSelf().each(function() {
    alert(this.nodeName); //alerts body, div, div, span
});?
Run Code Online (Sandbox Code Playgroud)

注意:andSelf已被弃用,现在是别名addBack(),应该与jQuery 1.8及更高版本一起使用

你可以在这里尝试一下,这个body部分是你没有得到它<head>和它的内容等.