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
?
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
?
Yes you can, using getAttribute()
, for example :
element.getAttribute('attribute-name'); //return 'attribute-name' attribute
NOTE: It's better to pass the object of current clicked element this
then get the attribute you want :
HTML :
<button name="X" data-other-attr='XX' onClick="reply_click(this)">Button</button>
JS :
function reply_click(clicked_object)
{
alert(clicked_object.getAttribute('name'));
alert(clicked_object.getAttribute('data-other-attr'));
}
Hope this helps.
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:
e.target
)e.currentTarget
)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>
Below is slightly modified code of example you pointed out in the question.
<html>
<body>
<form>
<button id="1" name="test1" onClick="reply_click(1)">B1</button>
<button id="2" name="test2" onClick="reply_click(2)">B2</button>
<button id="3" name="test3" onClick="reply_click(3)">B3</button>
<script>
function reply_click(clicked_id)
{
//alert(clicked_id);
var temp = document.getElementById(clicked_id).getAttribute("name");
alert(temp);
}
</script>
</form>
</body>
</html>
Yes, you can.
In the example you referenced:
<button id="1" onClick="reply_click(this.id)">B1</button>
You could replace this.id
with this.name
or this.dataset
and you would be passing those attributes to the reply_click
function instead of the ID.
You want to attach a click handler to the button (button.addEventListener('click')
), and then access its properties using dot notation just like a regular JavaScript object.
Fiddle: https://jsfiddle.net/9vkrwxmx/