user563892
user563892

Reputation:

Loop through DOM of HTML with jQuery

I want to loop through all the elements in the DOM structure of a html page with jQuery. Basically only the elements within the body tags are needed.

The reason I want to do this is because I want to fetch the positions of every element in the body structure.

I googled around and I found no answer to my question.

Your help is much appreciated.

Upvotes: 3

Views: 4896

Answers (3)

roryf
roryf

Reputation: 30170

$('body *').each(function() {
    // do stuff
});

If you have inline <script> tags and the like, you can add a :not selector to exclude those:

$('body *:not(script, style, noscript)').each(function() {
    // do stuff
});

As pointed out in the comments and the jQuery all selector docs, this probably won't perform very well. I haven't done any empirical testing, but this might perform better:

$('body').find('*').not('script, style, noscript').each(...);

Upvotes: 9

Andy E
Andy E

Reputation: 344773

Probably the best performing solution would be to use getElementsByTagName instead of a jQuery selector:

$(document.body.getElementsByTagName("*")).each(function () {
     // Do something here
});

Combining * in a selector with anything is generally not a good idea, as pointed out in the jQuery docs themselves:

Caution: The all, or universal, selector is extremely slow, except when used by itself.

http://api.jquery.com/all-selector/

If you really wanted to, you could use any of these variations, though none of them will give you as good performance as getElementsByTagName:

$(document.body).find("*");
$("body").find("*");
$("*", document.body);

Upvotes: 5

JB Nizet
JB Nizet

Reputation: 692191

Use the all selector :

$("body *").each(...)

Upvotes: 0

Related Questions