views:

52

answers:

3

Hi!

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

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

+9  A: 
var allOfThem = $('*');

You don't really need jQuery for this:

var allOfThem = document.getElementsByTagName('*');
Pointy
does the universal selector query text-nodes aswell ?
jAndy
No - to get all text nodes via jQuery, I think you'd have to work at it. You'd have to work down the tree finding them either through DOM APIs or with jQuery `.contents()`.
Pointy
A: 

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

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

warpech
+1  A: 

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

$('*') 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.

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

Shadow Wizard
document.getElementsByTagName("*") will return all DOM elements as "actual" elements, // lie. Sometimes it is seemingly impossible to enumerate all actual elements at certain step. Refer to my DOM/Gmail questions, and look for long code to enumerate all elements from all frames.
mhambra