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
2009-05-10 07:30:00
+1 for not recommending jQuery.
Tomalak
2009-05-10 07:35:45
It's best to use a standard "for" loop—"for in" loops are meant for iterating through objects.
Steve Harrison
2009-05-10 07:37:02
@Steve - Good catch!
Jose Basilio
2009-05-10 07:42:22
Also, caching the array's length improves performance. For example: "for (var i = 0, l = divs.length; i < l; i++)"...
Steve Harrison
2009-05-10 07:44:19
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
2009-05-10 07:44:58
Where's does Sam Lee find the property he wants in this answer?
KooiInc
2009-05-10 07:55:51
+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
2009-05-10 07:36:39
A:
You might also be able to use a selector engine such as Sizzle.
Steve
Steve Harrison
2009-05-10 07:37:50
or jQuery $("div").each(function (i) { if (this.style.color != "blue") { this.style.color = "blue"; } else { this.style.color = ""; } });
01
2009-05-10 08:07:42
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
2009-05-10 08:27:26