October 22, 2024
Chicago 12, Melborne City, USA
HTML

How to apply one function to all elements with the same class


I want to click on any of the 3 buttons, and they all will change their background colors at the same time. What is missing or needed to change in my code, for the addEventListener to be able to apply in all elements with the same class?

const one = document.getElementsByClassName('one');

one.forEach((element) => {    
    element.addEventListener("click", () => {
      if (element.style.backgroundColor = "#DCDCDC") {
        element.style.backgroundColor = "#56F1FF";
      } else {
        element.style.backgroundColor = "#DCDCDC";
      }
     })
 });
.one {
  background-color: #DCDCDC;
}

.one:hover {
  background-color: #56F1FF;
}
<button class="one">Catch</button>
<button class="one">Change</button>
<button class="one">Choose</button>



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video