What is the "fastest" (most efficient) way to have all elements of the body in an array and afterwards loop through each one of them?
Asked
Active
Viewed 9,379 times
4
-
2Do you want the full DOM tree or just its first level? – napolux Oct 19 '13 at 17:06
-
Do you need the array afterwards or you just want to iterate over all nodes? – plalx Oct 19 '13 at 17:21
4 Answers
3
You can use star selector in jquery.
var allElems=$('body').find('*');
allElems will be array like object so you can make a for loop on it or you can use jquery each method to go through all. like
allElems.each(function(){
var elm=this, //javascript DOM object
$elm=$(this) //jquery object for element.
});
If you just want to do with javascript you can use querySelectorAll dom method.
var allElems=document.body.querySelectorAll('*'); // new browser support
or
var allElems=document.body.getElementsByTagName('*'); //all browser support
Than you can use for loop to go through all elements.

Sudhanshu Yadav
- 2,323
- 18
- 18
3
I'd suggest this:
var items = document.body.getElementsByTagName("*");
for (var i = 0, len = items.length; i < len; i++) {
// do something with items[i] here
}

jfriend00
- 683,504
- 96
- 985
- 979
2
You can use:
var els = document.body.querySelectorAll( '*' ),
len = els.length, i = 0;
for ( ; i < len; i++ )
console.log( els[i] );
Browser Support for querySelectorAll: http://caniuse.com/#feat=queryselector
It's interesting to note that querySelectorAll
returns static NodeLists, differently from getElementsByTagName
, which returns live NodeLists.

jonathancardoso
- 11,737
- 7
- 53
- 72
-2
It would be something like this:
var allElements = $(body).find('*');
allElements.each(function(){
//do something
})

CodeTrooper
- 1,890
- 6
- 32
- 54