I am trying to assign a click event for each element that has a class name of director__card--iconBox
. The way that I am selecting these elements is by getElementsByClassName
. With the current code written, I am testing the function to apply a background-color
of its parents div to red. The end goal is to be able to flip the div and to display the backside of the div that will come later.
const toggleButton = document.getElementsByClassName("director__card--iconBox");
toggleButton.forEach((el) =>
el.addEventListener("click", (event) => {
const card = event.target.parentElement.querySelector(".director__card");
card.classList.toggle("open");
})
);
I am getting back an HTMLCollection. My thoughts is that this won't work because of an HTMLCollection? I have tried querySelectorAll to bring back a Node List, yet the NodeList returns empty..
HTMLCollection is an array-like object but it does not have forEach
method.
There are multiple ways you can iterate it with;
e.g.
Create an array out of it;
Array.from(toggleButton).forEach((el) =>
el.addEventListener("click", (event) => {
const card = event.target.parentElement.querySelector(".director__card");
card.classList.toggle("open");
})
);
Use for..of
for (let item of toggleButton) {
item.forEach((el) =>
el.addEventListener("click", (event) => {
const card = event.target.parentElement.querySelector(".director__card");
card.classList.toggle("open");
});
);
}
Or, just for
loop.
for (let i = 0, len = toggleButton.length; i < len; i++) {
toggleButton[i].forEach((el) =>
el.addEventListener("click", (event) => {
const card = event.target.parentElement.querySelector(".director__card");
card.classList.toggle("open");
});
);
}