Snow Crash Snow Crash - 2 months ago 5
Javascript Question

JavaScript - get attributes of clicked button

This answer explains how you can get the ID of a clicked button.

JavaScript - onClick to get the ID of the clicked button

However, can you also get other attributes of that button? E.g.

name
or
data-* attributes
?

Answer

can you also get other attributes of that button?

In the click handler you have access to the event data which gives you access to:

  • the DOM node that triggered the event (e.target)
  • the DOM node that the event was bound to (e.currentTarget)
  • all other event data (such as which mouse button was used for click events, event type, etc…)

The DOM node references have APIs for accessing data such as their attributes

Additionally the DOM node that the event was bound to is available by default as the calling context of the callback function. That's a really fancy way of saying that the DOM node will be set to the this variable:

document.querySelector('button').addEventListener('click', function () {
  console.log(this);
}, false);
<button type="button">example</button>

When you're using inline event handlers in HTML (which you should avoid), this is available to be passed to any functions you may want to call:

function click(btn) {
  console.log(btn);
}
<button type="button" onclick="window.click(this);">example</button>

Comments