Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.querySelectorAll('.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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are couple of things wrong here.

  1. document.getElementsByClassName returns a HTMLCollection that doesn’t have access to forEach method. You have to convert it into an array before using forEach.

  2. element.style.backgroundColor returns a RGB value, you can’t compare it with HEX code.

Here is the correct way to fix this

const btnCollection = document.getElementsByClassName('one');
const buttons = Array.from(btnCollection);  // Convert to an array

buttons.forEach((element) => {
    element.addEventListener("click", () => {
        if (element.style.backgroundColor === "rgb(220, 220, 220)") {  
            buttons.forEach((btn) => btn.style.backgroundColor = "#56F1FF");  
        } else {
            buttons.forEach((btn) => btn.style.backgroundColor = "#DCDCDC");  
        }
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading