So i’ve written a piece of code where there are 9 divs and I’ve given them ".spaces" classes and i want them to change their color if they are clicked on. But only the first div changes it’s color to red while the others don’t no matter how many times i click on them.
THIS IS THE HTML
<body>
<div id="playground">
<div id="play-spaces" class = "spaces"></div>
<div id="play-spaces" class = "spaces"></div>
<div id="play-spaces" class = "spaces"></div>
<div id="play-spaces" class = "spaces"></div>
<div id="play-spaces" class = "spaces"></div>
<div id="play-spaces" class = "spaces"></div>
<div id="play-spaces" class = "spaces"></div>
<div id="play-spaces" class = "spaces"></div>
<div id="play-spaces" class = "spaces"></div>
</div>
<script src="script.js"></script>
THIS IS THE JAVASCRIPT
const spaces = document.querySelector(".spaces");
spaces.addEventListener("click",function(){
console.log("Space has been clicked");
spaces.style.backgroundColor = "red";
})
I was expecting that when i click on a div then that particular div will change it’s color.
2
Answers
You can try this:-
ok uhh "document.querySelector(".spaces")", will only select the first element with the class "spaces". To fix it, you can use "document.querySelectorAll(".spaces")" to select all elements with the class "spaces".