How, when clicking on an element, add a class to all elements with the same class?

  • 0
    How to add a class to all elements with the same class when clicking on an element?
    There are five squares (they have the same class), when you click on one of them, add a class to all elements, for example, the "green" class.
    It turned out to be done only for the first element (when you click on the first square everything works, the rest do not)

    <div class="wrapper-square">
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
        </div>

    var elCollection = document.querySelector(".square");
        var elNodes = document.querySelectorAll(".square");
    
        elCollection.addEventListener("click", function(event) {
          event.preventDefault();
          elNodes.forEach((el) => {
            el.classList.toggle("green");
          });
        });

    .wrapper-square{
        display: flex;
    }
    
    .square{
        width: 100px;
        height: 100px;
        background-color: red;
        margin-right: 100px;
        cursor: pointer;
    }
    .green{
        background-color: green;
    }


    looked through questions on this topic, but could not figure it out, thanks in advance for the answer
    JavaScript Anonymous, Mar 3, 2020

  • 1 Answers
  • 0
    const elNodes = document.querySelectorAll (". square");



    elNodes.forEach (el = & gt; {

    el.addEventListener ("click", () = & gt; {

    el.classList.toggle ("green");

    });

    });
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!