-1

Is it possible to create a function that returns which button was pressed, even though all buttons have the same class?
It is important that the classes of the buttons must not be changed.

<html>
 <body>
   <button class="button">text</button>
   <button class="button">text</button> //this button was clicked
   <button class="button">text</button>
 </body>
</html>

The code is only for visualisation I know it isn't right.

function myfunction(){
 console.log(clickedbutton)
}

What I have to fill in so the code runs?
Sorry for the bad code i don't know how to make it more clearly.

MoDi
  • 66
  • 7

5 Answers5

1

Hello and happy new 2021!

I think this might be a slight duplicate of this.

As Gabriele said, you can get the HTML element by using the target. If you need some logic for differentiating the structures (using them in some state later on), you would need to assign an id or a different class.

0

Delegate

document.getElementById("buttonDiv").addEventListener("click",function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("button")) console.log(tgt.textContent,"clicked")
})
<div id="buttonDiv">
   <button class="button">text 1</button>
   <button class="button">text 2</button>
   <button class="button">text 3</button>
</div>   
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

When an event happens and the handler that is bound to that event for that element is called, it is passed the event as the first parameter. And one of the properties of the event is the target which points to the element that triggered the event.

so

function clickHandler(event) {
  const clickedElement = event.target;
  console.log(clickedElement.textContent);
}

document
  .querySelectorAll('.button')
  .forEach(button => button.addEventListener('click', clickHandler))
<button class="button">text 1</button>
<button class="button">text 2</button>
<button class="button">text 3</button>
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

If you assign a function to the onClick event of a button (or multiple buttons), you can receive the event info as an argument, like so:

function myfunction(e) {
  console.log(e.target.id)
}
<!DOCTYPE html>
<html>

<body>
  <button id="button-1" class="button" onclick="myfunction(event)">text</button>
  <button id="button-2" class="button" onclick="myfunction(event)">text</button>
  <button id="button-3" class="button" onclick="myfunction(event)">text</button>
</body>

</html>
0

You can make use of data-id for getting index of button clicked.

const button = document.querySelectorAll(".button");


function getClickedIndex(evt) {
  console.log(evt.target.getAttribute("data-id"));
}


button.forEach(button => button.addEventListener('click', getClickedIndex))
<html>
 <body>
   <button class="button" data-id="1">text</button>
   <button class="button" data-id="2">text</button>
   <button class="button" data-id="3">text</button>
 </body>
</html>
sourav satyam
  • 980
  • 5
  • 11