Iterating through all the <div> tags on a page
-
20-08-2019 - |
Question
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?
Solution
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...";
}
OTHER TIPS
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
}
}
You might also be able to use a selector engine such as Sizzle.
Steve
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow