skip to Main Content

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


  1. You can try this:-

    <body>
    <div id="playground">
        <div class="spaces"></div>
        <div class="spaces"></div>
        <div class="spaces"></div>
        <div class="spaces"></div>
        <div class="spaces"></div>
        <div class="spaces"></div>
        <div class="spaces"></div>
        <div class="spaces"></div>
        <div class="spaces"></div>
    </div>
    <script>
        const spaces = document.querySelectorAll(".spaces");
    
        spaces.forEach(space => {
            space.addEventListener("click", function() {
                console.log("Space has been clicked");
                this.style.backgroundColor = "red";
            });
        });
    </script>
    
    Login or Signup to reply.
  2. 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".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search