views:

1006

answers:

3

I want to go through all the elements on a page using Javascript and see if they have a property set. Is there an easy way to do this, or do I have to use a recursive solution?

+11  A: 

You can use:

var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
   //do something to each div like
   divs[i].innerHTML = "something new...";
}
Jose Basilio
+1 for not recommending jQuery.
Tomalak
It's best to use a standard "for" loop—"for in" loops are meant for iterating through objects.
Steve Harrison
@Steve - Good catch!
Jose Basilio
Also, caching the array's length improves performance. For example: "for (var i = 0, l = divs.length; i < l; i++)"...
Steve Harrison
Can I just add that counting down from divs.length-1 to 0, rather than up, will be slightly faster, not noticeable most of the time, but it could come in handy to remember that at some point.
scragar
Where's does Sam Lee find the property he wants in this answer?
KooiInc
+4  A: 

To find a property in one or more of all divs on a page:

var divs = document.getElementsByTagName("div"), i=divs.length;
while (i--) {
   if (divs[i].getAttribute([yourProperty]) === 'yourValue'){
      //do something
   } 
}
KooiInc
A: 

You might also be able to use a selector engine such as Sizzle.

Steve

Steve Harrison
or jQuery $("div").each(function (i) { if (this.style.color != "blue") { this.style.color = "blue"; } else { this.style.color = ""; } });
01
I don't think your comment is related to my answer—it doesn't make use of any selectors. Why don't you post your jQuery code as another answer?
Steve Harrison