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 :
There are couple of things wrong here.
-
document.getElementsByClassNamereturns aHTMLCollectionthat doesn’t have access toforEachmethod. You have to convert it into an array before usingforEach. -
element.style.backgroundColorreturns 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");
}
});
});