For some reason, the contents nodelist value becomes undefined. The first console.log in my code below returns false and the second returns true, I don't understand why this happens but I suspect that is because it believes that the variable is local. However, even when I copy the document.querySelectorAll code into the function it still evaluates to undefined and I get an error saying that it cannot read the style property of undefined in the if statement. I have checked that the length of both nodelists are the same.
var headers, contents;
window.onload = function () {
headers = document.querySelectorAll(".toggleMenuSection .sectionHeader");
contents = document.querySelectorAll(".toggleMenuSection .sectionContent");
for (var i = contents.length - 1; i >= 0; i--) {
contents[i].style.display = 'none';
console.log(contents[i]==undefined);
headers[i].onclick = function(){
console.log(contents[i]==undefined);
if(contents[i].style.display == 'block') contents[i].style.display = 'none';
else contents[i].style.display = 'block';
};
}
Just to clarify, the question here is why does a variable with a value suddenly have a value of undefined when I haven't changed it. In this case the contents[i] values.