I want to add an event listener to each of the div elements with the class "box" here:
<div >
<div >
<p >Click in a box to play. Crosses start.</p>
</div>
<div >
<div id="0"></div>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
</div>
<div >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.
CodePudding user response:
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:
<body>
...
<div >
...
</div>
<script>
let elementsArray = document.querySelectorAll(".box");
elementsArray.forEach(function(div) {
div.addEventListener("click", function() {
alert("AA");
});
});
</script>
</body>
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 a console.log
statement, like this:
let elementsArray = document.querySelectorAll(".box");
console.log(elementsArray);
elementsArray.forEach(function(div) {
div.addEventListener("click", function() {
alert("AA");
});
});
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 the elementsArray
variable contains the elements you expect.
CodePudding user response:
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.
window.addEventListener("click", (e) => {
if (e.target.classList.contains("box")) {
console.log(e.target.id);
}
});