0

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.

  • 1
    See this question: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Zirak Jan 02 '16 at 15:16
  • While the duplicate suggests you use functions to make a new variable scope in each iteration of the loop, since all you need is the primitive value `i`, I would just put it as a property on each `headers[i]` element. Like: `headers[i].__index = i`. Then in the handler, do `contents[this.__index].style.display...` –  Jan 02 '16 at 15:20
  • And by the way, if `headers` and `contents` have the same length, you can get by with one loop. If not, and if there may be more `headers` than `contents`, you'll need to verify that the `contents` index exists before trying to get the `.style` property. –  Jan 02 '16 at 15:24
  • I don't understand, do I create a new function that takes the index as the parameter? – Sayed Hajaj Jan 02 '16 at 15:39
  • Why is the element becoming undefined in the onclick function but not just before? – Sayed Hajaj Jan 02 '16 at 15:42
  • Thanks about the loop by the way, I will edit my code to do it in one loop. – Sayed Hajaj Jan 02 '16 at 16:01
  • Can someone also explain how it is a duplicate, my question is why a global variable loses its value once I try to access it from within another function and that doesn't seem like the issue in the other question to me. Or am I missing something? – Sayed Hajaj Jan 02 '16 at 16:31

0 Answers0