/ JAVASCRIPT, FRONT-END

How to get data attribute value from the element in Javascript?

Question

There is a html as below.

<a id="option1" data-id="10" data-option="21" href="#">
       Click to do something
</a>

I want to get the data-id and data-option values while clicking this element.

How to make it happen?

Answer

Solution:

$('#option1').on('click', function () {
    var $el = $(this);
    
    console.log($el.data('id'), $el.data('option'));
});

The console log will be 10 and 21.

Reference


This is the end of post