This is probably very simple, but I cannot make it work. I have 2 headings with the same class
<h1 class="heading-title">Hyperspace</h1>
<h1 class="heading-title">Hyperspace</h1>
I also have a button that I want to change both the headings color when I click it
const customColor1Btn = document.querySelector(".custom-color-1");
const headings = document.querySelectorAll(".heading-title");
customColor1Btn.addEventListener("click", function () {
headings.style.color = "red";
});
It works when I change the color of just 1 heading, but I can never make an event listener work with more than 1 element. I need 1 button click to manipulate multiple element's styles.
How can I make it work?
Document.querySelectorAll returns a NodeList
So, you need to loop over all the headings in the headings NodeList and change the color for the individual heading nodes.
const customColor1Btn = document.querySelector(".custom-color-1");
const headings = document.querySelectorAll(".heading-title");
customColor1Btn.addEventListener("click", function () {
headings.forEach(h => h.style.color = "red");
});
<h1 class="heading-title">Hyperspace</h1>
<h1 class="heading-title">Hyperspace</h1>
<button class="custom-color-1">Change color</button>