I have A html element and would like to read data attribute in OnClick event
<a id="downloadFile" class="btn btn-success" href="javascript:;" data="MyData">Download file</a>
If I use code below this refer to href atribute and not to A element. How to refer to A element and read data value?
$('#downloadFile').click(function() {
alert(this.attr('data')); //I get error that 'href' do not has 'data' attribute, this code refers to href attribute and not to A element
});
In the context of an event handler,
thisrefers to the DOM element, not the jQuery object. Use$(this)to get a jQuery object so that you can use theattrfunction:Another option is to use
this.getAttribute("data").DEMO.