gpt4 book ai didi

javascript - 如何遍历页面上的所有 DOM 元素?

转载 作者:IT老高 更新时间:2023-10-28 13:20:15 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以通过 * getElementsByTagName() 这样它将返回页面中的所有元素:

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

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

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

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

这肯定会加快现代浏览器的速度。


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

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 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4256339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com