Javascript:如何遍历页面上的所有 DOM 元素? [英] Javascript: How to loop through ALL DOM elements on a page?

查看:29
本文介绍了Javascript:如何遍历页面上的所有 DOM 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历页面上的所有元素,因此我想检查此页面上存在的每个元素是否有一个特殊的类.

那么,我怎么说我想检查每个元素?

解决方案

你可以传递一个 *getElementsByTagName() 以便返回页面中的所有元素:

var all = document.getElementsByTagName("*");for (var i=0, max=all.length; i < max; i++) {//对这里的元素做一些事情}

请注意,您可以使用 querySelectorAll(),如果它可用(IE9+,IE8 中的 CSS),只查找具有特定类的元素.

if (document.querySelectorAll)var clsElements = document.querySelectorAll(.mySpeshalClass");别的//循环遍历所有元素

这肯定会加快现代浏览器的处理速度.


浏览器现在支持 NodeList 上的 foreach.这意味着您可以直接循环元素,而无需编写自己的 for 循环.

document.querySelectorAll('*').forEach(function(node) {//对节点对象做任何你想做的事情.});

<块引用>

性能说明 - 通过使用特定选择器,尽最大努力确定您要寻找的范围.根据页面的复杂性,通用选择器可以返回大量节点.另外,当您不关心 子项时,请考虑使用 document.body.querySelectorAll 而不是 document.querySelectorAll.>

I'm trying to loop over ALL elements on a page, so I want to check every element that exists on this page for a special class.

So, how do I say that I want to check EVERY element?

解决方案

You can pass a * to getElementsByTagName() so that it will return all elements in a page:

var all = document.getElementsByTagName("*");

for (var i=0, max=all.length; i < max; i++) {
     // Do something with the element here
}

Note that you could use querySelectorAll(), if it's available (IE9+, CSS in IE8), to just find elements with a particular class.

if (document.querySelectorAll)
    var clsElements = document.querySelectorAll(".mySpeshalClass");
else
    // loop through all elements instead

This would certainly speed up matters for modern browsers.


Browsers now support foreach on NodeList. This means you can directly loop the elements instead of writing your own for loop.

document.querySelectorAll('*').forEach(function(node) {
    // Do whatever you want with the node object.
});

Performance note - Do your best to scope what you're looking for by using a specific selector. A universal selector can return lots of nodes depending on the complexity of the page. Also, consider using document.body.querySelectorAll instead of document.querySelectorAll when you don’t care about <head> children.

这篇关于Javascript:如何遍历页面上的所有 DOM 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆