javascript 使用 jQuery 获取所有 DOM 元素的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4024027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:11:39  来源:igfitidea点击:

Best Way to Get All DOM Elements with jQuery

javascriptjqueryjquery-selectors

提问by DLiKS

What's the best way to get all of the DOM elements on a page using jQuery?

使用 jQuery 获取页面上所有 DOM 元素的最佳方法是什么?

Thanks,

谢谢,

DLiKS

德利克斯

Edit: This is for use in a script that grayscales an entire page using grayscale.js - http://james.padolsey.com/demos/grayscale/. jQuery because I can! :P

编辑:这用于使用 grayscale.js 对整个页面进行灰度化的脚本 - http://james.padolsey.com/demos/grayscale/。jQuery 因为我可以!:P

回答by Pointy

var allOfThem = $('*');

You don't really need jQuery for this:

你真的不需要jQuery:

var allOfThem = document.getElementsByTagName('*');

回答by Shadow Wizard is Ear For You

document.getElementsByTagName("*")will return all DOM elements as "actual" elements, with all their contents and properties and everything.

document.getElementsByTagName("*")将所有 DOM 元素作为“实际”元素返回,包括它们的所有内容和属性以及所有内容。

$('*')or $("body *")will return array of "jQuery objects", each only pointing on true element. To get the true element, you'll have to use the specific jQuery object.

$('*')$("body *")将返回“jQuery 对象”数组,每个对象只指向真正的元素。要获得真正的元素,您必须使用特定的 jQuery 对象。

Guess this difference is what causing this behavior of browser crashing when getting all elements vs. getting all jQuery objects.

猜猜这个差异是什么导致浏览器在获取所有元素与获取所有 jQuery 对象时崩溃的行为。

回答by warpech

It seems you want $("body *"), which is equivalent to document.documentElement.getElementsByTagName('*')

看来你想要$("body *"),这相当于document.documentElement.getElementsByTagName('*')

Weirdly, getElementsByTagName('*')seems to crash my Firefox/Firebug, while jQuery version works fine

奇怪的是,getElementsByTagName('*')似乎使我的 Firefox/Firebug 崩溃,而 jQuery 版本工作正常