Search code examples
javascripthtmlqueryselectall

querySelectorAll for any div within an element


I'd expect this to pop up an alert for any div I click inside the section id playGrid, but it does nothing.

<div id="playGrid" class="w">
  <section>
    <div id="0_0"></div>
    <div id="0_1"></div>
    <div id="0_2"></div>
    <div id="0_3"></div>

    <div id="1_0"></div>
    <div id="1_1"></div>
    <div id="1_2"></div>
    <div id="1_3"></div>

    <div id="2_0"></div>
    <div id="2_1"></div>
    <div id="2_2"></div>
    <div id="2_3"></div>

    <div id="3_0"></div>
    <div id="3_1"></div>
    <div id="3_2"></div>
    <div id="3_3"></div>
  </section>
</div>

JavaScript

document.getElementById("playGrid").querySelectorAll('section div').forEach(function(el){
  el.addEventListener('click', function() {
    alert(this.id);
  });
});

Solution

  • I think the problem is that your code runs before the document is fully loaded. To run your code after page is loaded add event listener for 'DOMContentLoaded' event:

    document.addEventListener('DOMContentLoaded', function(){
      document.getElementById("playGrid").querySelectorAll('section div').forEach(function(el) {
        el.addEventListener('click', function() {
          alert(this.id);
        });
      });
    });
    

    https://codepen.io/mikhailsidorov/pen/BaoPKoX