javascripthoistingnodelist

JavaScript: can't immediately select elements after creating them?


My script contains the following code that is causing me issues:

btn.addEventListener('click', ()=> {
  if (!gamePlay) {
    setup()
    let word=document.querySelectorAll('box')
    console.log(word)
    btn.classList.toggle('hidden')
    gamePlay=true
  }
})

After all the div elements are created in the function setup(), I am trying to select them by their class name (box) however the node list from the section is an empty node list (which is also shown in the console).

I am assuming the code is synchronous. I just can't seem to access the elements created by the call to setup().


Solution

  • You are able to access and query document elements immediately after they are created.

    The issue here is that you selector syntax is incorrect; to select the elements with box class, prefix the selector with a ".":

    btn.addEventListener('click', () => {
    
      if (!gamePlay) {
    
        setup();
    
        let word = document.querySelectorAll('.box'); // Prefix .
        console.log(word);
        btn.classList.toggle('hidden');
    
        gamePlay = true;
      }
    })