Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu June 03, 2023 . #Button . #for-loop

How to check which button is clicked in JavaScript

Hello programmers, in this article you will learn how you can check which of the many buttons is clicked using forEach() method in JavaScript. Suppose, you have four buttons button 1, button 2, button 3, and button 4 . Do something different for the button that users will click on.

The first thought that comes to your mind is to call a different function for each button. The example is given below.

Call different function for each button
 <button onclick="function1()">button 1</button>
 <button onclick="function2()">button 2</button>
 <button onclick="function3()">button 3</button>
 <button onclick="function4()">button 4</button>
Try it Yourself »

If that's what you think, then your answer is correct but elegant for just a few buttons. But, If you have a lot of buttons, the above approach is not elegant.

So, In this post, I shall detect which button is clicked using javascript loop dynamically.

Detect which button is clicked using for loop

Check which button is clicked using for loop
let buttonList = document.querySelectorAll(".button");
  for (let i = 0; i <buttonList.length; ++i) {
    buttonList[i].addEventListener("click", function() {
      alert(this.innerHTML +" is clicked");
    });
  }
Try it Yourself »
  1. Create button elements (as much as you want) with the same class named button.
  2. Store the all button elements into a variable as an array using querySelectorAll() method. eg. let buttons = document.querySelectorAll(".button");
  3. Create a for loop and inside the for loop just add a click event listener to all the buttons dynamically.

You can also pass a parameter. eg.

Dynamically button onclick event inside for loop
for (let i = 0; i <buttonList.length; ++i) {
    buttonList[i].addEventListener("click", function(e) {
      alert(e.target.innerHTML +" is clicked");
    });
  }
Try it Yourself »

Check which button is clicked using forEach() method.

Call different function for each button

You can also use forEach() method instead of for loop. The example is given below.

  let buttonList = document.querySelectorAll(".button");
  buttonList.forEach(function(i){
    i.addEventListener("click", function(e){
     alert(e.target.innerHTML);
    })
  })
Try it Yourself »
save
listen
AI Answer
Write Your Answer
loading
back
View All