Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - get attributes of clicked button

Tags:

javascript

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 ?

like image 767
Snowcrash Avatar asked Dec 06 '22 16:12

Snowcrash


1 Answers

Working fiddle.

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.

like image 129
Zakaria Acharki Avatar answered Dec 21 '22 05:12

Zakaria Acharki