Iterating through all the <div> tags on a page

73,575

Solution 1

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...";
}

Solution 2

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
   } 
}

Solution 3

Using JS ES6 For ... of

for (elem of document.getElementsByTagName('div')){
  elem.style.marginTop='20px'
}
Share:
73,575
Sam Lee
Author by

Sam Lee

Updated on July 09, 2022

Comments

  • Sam Lee
    Sam Lee almost 2 years

    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?

  • Steve Harrison
    Steve Harrison almost 15 years
    Also, caching the array's length improves performance. For example: "for (var i = 0, l = divs.length; i < l; i++)"...
  • scragar
    scragar almost 15 years
    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.
  • KooiInc
    KooiInc almost 15 years
    Where's does Sam Lee find the property he wants in this answer?
  • IAdapter
    IAdapter almost 15 years
    or jQuery $("div").each(function (i) { if (this.style.color != "blue") { this.style.color = "blue"; } else { this.style.color = ""; } });
  • Steve Harrison
    Steve Harrison almost 15 years
    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?