我试图在一个页面上循环所有元素,所以我想检查存在于这个页面上的一个特殊类的每个元素。

我怎么说我要检查每个元素呢?


当前回答

最好的解决方案是使用递归:

loop(document);
function loop(node){
    // do some thing with the node here
    var nodes = node.childNodes;
    for (var i = 0; i <nodes.length; i++){
        if(!nodes[i]){
            continue;
        }

        if(nodes[i].childNodes.length > 0){
            loop(nodes[i]);
        }
    }
}

与其他建议不同的是,这个解决方案不需要为所有节点创建一个数组,因此内存占用更少。更重要的是,它能发现更多的结果。我不确定这些结果是什么,但在chrome上测试时,它发现比document.getElementsByTagName("*")多50%的节点;

其他回答

下面是另一个关于如何循环遍历文档或元素的示例:

function getNodeList(elem){
var l=new Array(elem),c=1,ret=new Array();
//This first loop will loop until the count var is stable//
for(var r=0;r<c;r++){
    //This loop will loop thru the child element list//
    for(var z=0;z<l[r].childNodes.length;z++){

         //Push the element to the return array.
        ret.push(l[r].childNodes[z]);

        if(l[r].childNodes[z].childNodes[0]){
            l.push(l[r].childNodes[z]);c++;
        }//IF           
    }//FOR
}//FOR
return ret;
}

我觉得这真的很快

document.querySelectorAll('body,body *').forEach(function(e) {

你可以试试 document.getElementsByClassName(“special_class”);

最好的解决方案是使用递归:

loop(document);
function loop(node){
    // do some thing with the node here
    var nodes = node.childNodes;
    for (var i = 0; i <nodes.length; i++){
        if(!nodes[i]){
            continue;
        }

        if(nodes[i].childNodes.length > 0){
            loop(nodes[i]);
        }
    }
}

与其他建议不同的是,这个解决方案不需要为所有节点创建一个数组,因此内存占用更少。更重要的是,它能发现更多的结果。我不确定这些结果是什么,但在chrome上测试时,它发现比document.getElementsByTagName("*")多50%的节点;

我也在找。嗯,不完全是。我只想列出所有DOM节点。

var currentNode,
    ni = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);

while(currentNode = ni.nextNode()) {
    console.log(currentNode.nodeName);
}

要获取具有特定类的元素,可以使用过滤器函数。

var currentNode,
    ni = document.createNodeIterator(
                     document.documentElement, 
                     NodeFilter.SHOW_ELEMENT,
                     function(node){
                         return node.classList.contains('toggleable') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
                     }
         );

while(currentNode = ni.nextNode()) {
    console.log(currentNode.nodeName);
}

找到的解 中数