Home > front end >  How to change background colours of buttons on click [duplicate]
How to change background colours of buttons on click [duplicate]

Time:09-26

I am a beginner and want to know how do I change the background colours of all the buttons on click?

var buttons = document.querySelectorAll(".btn").length;

for (var i = 0; i < buttons; i  ) {
  document.querySelectorAll(".btn")[i].addEventListener("click", function () {
    document.querySelectorAll(".btn").style.backgroundColor = "red";
  });
}
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>

CodePudding user response:

You need to change the style property for every item in your selection as shown here:

https://stackoverflow.com/a/33178161/2459156

CodePudding user response:

querySelectorAll returns a NodeList. You have to iterate through it and apply the style to each item:

var buttons = document.querySelectorAll(".btn").length;

for (var i = 0; i < buttons; i  ) {
  document.querySelectorAll(".btn")[i].addEventListener("click", function (e) {
    document.querySelectorAll(".btn").forEach(e => e.style.backgroundColor = "red")
  });
}
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>
<button class="btn">abc</button>

  • Related