Reputation: 352
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?
Upvotes: 4
Views: 9866
Reputation: 1888
It would be something like this:
var allElements = $(body).find('*');
allElements.each(function(){
//do something
})
Upvotes: -2
Reputation: 12707
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.
Upvotes: 2
Reputation: 2333
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.
Upvotes: 3
Reputation: 707308
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
}
Upvotes: 3