Reputation: 18107
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
});
Upvotes: 1
Views: 6457
Reputation: 1250
Only change THIS for the propper selector for Jquery
$('#downloadFile').click(function() {
alert($('#downloadFile').attr('data')); //Get error that href do not has data atribute, this refered to href atribute and not to A element
});
Upvotes: 0
Reputation: 74420
You are referring to js object using this but using jquery syntax.
Try:
$(this).attr('href')
Upvotes: 0
Reputation: 91309
In the context of an event handler, this
refers to the DOM element, not the jQuery object. Use $(this)
to get a jQuery object so that you can use the attr
function:
$('#downloadFile').click(function() {
alert($(this).attr('data'));
});
Another option is to use this.getAttribute("data")
.
DEMO.
Upvotes: 5
Reputation: 148120
You can have custom data attribute and separate it with -
<a id="downloadFile" class="btn btn-success" href="javascript:;" data-yourhref="MyData">Download file</a>
$('#downloadFile').click(function() {
alert($(this).data('yourhref')); //Get error that href do not has data atribute, this refered to href atribute and not to A element
});
Upvotes: 1