我试图遍历页面上的所有元素,所以我想检查这个页面上存在的每个元素是否有一个特殊的类。
那么,我怎么说我想要检查每个元素呢?
发布于 2014-10-03 09:33:37
也在找同样的东西。嗯,不完全是。我只想列出所有的DOM节点。
var currentNode,
ni = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);
while(currentNode = ni.nextNode()) {
console.log(currentNode.nodeName);
}
要获取具有特定类的元素,我们可以使用filter函数。
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);
}
在MDN上找到解决方案
发布于 2017-03-09 01:50:29
一如既往,最好的解决方案是使用递归:
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%的节点
发布于 2012-02-05 05:07:19
下面是关于如何遍历文档或元素的另一个示例:
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;
}
https://stackoverflow.com/questions/4256339
复制相似问题