Tomas
Tomas

Reputation: 18107

read element attribute in OnClick event

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

Answers (4)

manuerumx
manuerumx

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

A. Wolff
A. Wolff

Reputation: 74420

You are referring to js object using this but using jquery syntax.

Try:

$(this).attr('href')

Upvotes: 0

Jo&#227;o Silva
Jo&#227;o Silva

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

Adil
Adil

Reputation: 148120

You can have custom data attribute and separate it with -

Live Demo

<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

Related Questions