Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  121] [ 6]  / answers: 1 / hits: 63356  / 13 Years ago, thu, january 5, 2012, 12:00:00

Unfortunately I need to iterate over all the DOM elements of a page and I'm wondering what the most efficient technique is. I could probably benchmark these myself and might if I have the time but I'm hoping someone has already experienced this or has some options I hadn't considered.


Currently I'm using jQuery and doing this:


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

While it works, It seems to cause some lag on the client. It could also be tweaked with a more specific jQuery context like $('body', '*'). It occurred to me that native Javascript is usually faster than jQuery and I found this:


var items = document.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
// do stuff
}

I'm assuming the native option is faster. Wondering if there are other options I hadn't considered. Maybe a recursive option that iterates over child nodes in parallel.


More From » jquery

 Answers
63

The Vanilla Javascript way you posted is the fastest. It will be faster than the jQuery solution you posted (See my comment on the question). If you're not removing or adding anything to the DOM in your loop and order of traversal doesn't matter, you can also speed it up ever so slightly by iterating in reverse:



var items = startElem.getElementsByTagName(*);
for (var i = items.length; i--;) {
//do stuff
}


Edit: check this benchmark to see how much time you can save by using the native code: http://jsben.ch/#/Ro9H6


[#88210] Wednesday, January 4, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
jonrened questions
Mon, Nov 2, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
Tue, Jan 21, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
;