Silver_Bear Silver_Bear - 1 month ago 9
Javascript Question

Using querySelectorAll inside a for-in-loop

I'm feeling a little stupid to ask this because it should be so simple, but I'm getting pretty frustrated.

I have a few divs that I want to show only one at a time, so I want to hide the rest. My approach:

var elements = document.querySelectorAll("div");

for (i in elements) {
elements[i].style.setProperty("display", "none");
}


Firefox always says
elements[i].style.setProperty();
is undefined.
I've made a workaround using a normal for-loop without using
in
, but I'd still like to know why this doesn't work.

Thanks in advance!

Answer

Replace

elements[i].style.setProperty("display", "none");

with

elements[i].style.display = "none";

As the HTMLElement.style property returns a CSSStyleDeclaration object that represents the element's inline styles as properties, i.e. style.property = 'value'

And use a regular for loop when iterating over array-like objects that has a length, like nodeLists

var elements = document.querySelectorAll("div");

for ( var i=0; i<elements.length; i++) {
    elements[i].style.display = "none";
}
Comments