Home > front end >  How to change the colour of selected button when clicked using target method?
How to change the colour of selected button when clicked using target method?

Time:09-26

I am a beginner and want to know how do I change the colour of the selected clicked button using the target method?

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 use the event argument that you get from the click callback and the clicked element is the .target.

You can do:

document.querySelectorAll(".btn")[i].addEventListener("click", function (event) {
    event.target.style.backgroundColor = "red";
  });

But you can do instead:

const buttons = document.querySelectorAll(".btn");

buttons.forEach(btn => {
  btn.addEventListener("click", function (event) {
event.target.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:

Your code is currently very inefficient.

Inside the for loop, you are reselecting every button. You should instead select them once outside the loop.

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

for (var i = 0; i < buttons.length; i  ) {
  buttons[i].addEventListener("click", function (e) {
    e.target.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