Looping through JavaScript "getElementsByTagName()" object

html, javascript, object

Solution

You have an error in the console: `Uncaught TypeError: Cannot set property 'display' of undefined`

Try:

var wrapper = document.querySelector(".wrapper");

var divs = wrapper.getElementsByTagName("div");

for (i = 0; i < divs.length; ++i) {
   each = divs[i];
   if (each.classList.contains("test2")) {
    each.style.display = "none";
   }
}

Demo

Problem

How can I loop through an object returned from "getElementsByTagName()" on a selector correctly. I can't seem to get it right. For example, if I have a bunch of divs like this: ``` <div class="wrapper"> <div class="test1">this is a div</div> <div class="test2">this is a div</div> <div class="test1">this is a div</div> <div class="test2">this is a div</div> <div class="test1">this is a div</div> <div class="test2">this is a div</div> </div> ``` and I want to loop through the results from a "getElementsByTagName()" like this: ``` var wrapper = document.querySelector(".wrapper"); var divs = wrapper.getElementsByTagName("div"); for (i = 0; i < divs.length; ++i) { each = divs[i]; if (each.classList.contains("test2")) { this.style.display = "none"; } } ``` and here's a fiddle : http://jsfiddle.net/Y2Yzv/1/

Original source