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>
4
Answers
I clicked the "Run Code Snippet" button on your code and it returned with an error: "one.forEach is not a function" that’s your problem. try something different like a for loop or a while loop with variables (same thing). It may autocorrect into forEach for you if you have a library installed but you’re better off using a default javascript function
The call
document.getElementsByClassName
returns an array-like object, but not an array. See: MDN – getElementsByClassNameThe function
forEach
can only be called on an array.To fix this, you need to create an array from the array-like object, which can be achieved by using
Array.from
. See: MDN – Array.fromUpdate your JavaScript like this:
There are couple of things wrong here.
document.getElementsByClassName
returns aHTMLCollection
that doesn’t have access toforEach
method. You have to convert it into an array before usingforEach
.element.style.backgroundColor
returns a RGB value, you can’t compare it with HEX code.Here is the correct way to fix this
As explained
.forEach()
doesn’t exists onHTMLCollection
returned fromgetElementsByClassName
.But I would recommend potentially better approach of using a container: