I want to add an event listener to each of the div elements with the class "box" here:
<div class="gameBox">
<div class="msgs">
<p class="msg">Click in a box to play. Crosses start.</p>
</div>
<div class="gameTable">
<div class="box" id="0"></div>
<div class="box" id="1"></div>
<div class="box" id="2"></div>
<div class="box" id="3"></div>
<div class="box" id="4"></div>
<div class="box" id="5"></div>
<div class="box" id="6"></div>
<div class="box" id="7"></div>
<div class="box" id="8"></div>
</div>
<div class="reset">Reset</div>
</div>
let elementsArray = document.querySelectorAll(".box");
elementsArray.forEach(function(div) {
div.addEventListener("click", function() {
alert("AA");
});
});
This is the JavaScript I have used to do this, however it does not return anything. I think the issue may be that the div element is inside another div element because the code works when I take it out of the rest of my program. Please teach me the path to redemtion.
2
Answers
It looks like your code is correct. One thing you can try is to make sure that the script is being executed after the elements are added to the page. You can do this by placing your script at the end of the
<body>
element, just before the closing</body>
tag.Here’s an example:
This ensures that the elements with the
box
class are added to the page before your script runs.Another thing you can try is to add a debug statement to your code to see if the
elementsArray
variable is actually getting populated with the elements you expect. You can do this by adding aconsole.log
statement, like this:This will print the
elementsArray
variable to the JavaScript console, which you can access in your web browser. This will allow you to verify that theelementsArray
variable contains the elements you expect.One solution is to add an event listener to the
window
object instead, and check if the clicked element is one of these.box
elements.