How to get custom attribute using jQuery

We have a custom attribute on the flags in this case called data-ref.

How to get the value. This did not work.

this.attr('data-ref'); 

Any ideas

Wonderful

+7
source share
5 answers

Do you know that you have a discrepancy between your custom date-ref attribute in the text and "data-ref" in your jQuery?

Also, it might be easier for you to work with the jQuery object:

 $(this).attr('data-ref'); 

JS Fiddle demo .

The problem is that you are not using a jQuery object:

 this.attr('data-ref'); 

Unable to work

On the other hand, to retrieve the data-* attributes using the DOM, you have the following options:

 this.getAttribute('data-ref'); 

Or:

 this.dataset.ref; 

Or:

 this.dataset['ref']; 
+15
source

$ ("selector") atr ("link data."); should work definitely.

Maybe you can post your HTML

+2
source

perhaps you should use:

 $(this).attr('data-ref'); 

but it is not very beautiful! use jQuery.data () to store data on the DOM nodes.

for storage:

 $('#divid').data('data-ref', 'i am data'); 

To obtain:

 var data = $('#divid').data('data-ref'); 
+1
source

The previously declared attr () is how to get custom attributes. However, also note that if you use data- * HTML5 attributes, you can also use jQuery.data () to access this data:

http://api.jquery.com/data/

+1
source

Your implementation may be related to your use. maybe it should be $ (this), or you cannot get attached properly. I can not find any problems with him .. see http://jsfiddle.net/nvkVy/2/

 <a href='api.fatherstorm.com' data-ref='test' data:ref='test' data_ref='test' class='testable'>test me</a> <script> $(document).ready(function(){ $('.testable').click(function(){ alert('data-ref='+$(this).attr('data-ref')); alert('data:ref='+$(this).attr('data:ref')); alert('data_ref='+$(this).attr('data_ref')); return(false); }); }); </script> 
0
source

All Articles