Let us say you have the following HTML element.
<a id='myAnchor' data-id='myLink' data-text='hello world'>Hello World</a>
There several ways to get data-id attribute in jQuery.
1. Using attr()
You can easily get data-id attribute using attr() function. You need to use the right selector to select the element, and then call attr() function for it. The following command will return the text ‘myLink’.
You can also use the same method to get other data attributes also. Here is a command to get data-text attribute.
Please note, in attr() function, you need to use the entire data attribute’s name, including ‘data-‘ part. Mentioning ‘id’ alone will not work.
2. Using prop()
prop() function is similar to attr() and has the same syntax. You can get data attributes using prop() function as shown below.
$('#myAnchor').prop("data-id"); //returns myLink $('#myAnchor').prop("data-text"); //returns hello world
Please note, in prop() function also, you need to use the entire data attribute’s name, including ‘data-‘ part. Mentioning ‘id’ alone will not work.
3. Using data() function
You can also use data() function to get a specific data attribute’s value as shown below. It is supported since jQuery>=1.4.3
$('#myAnchor').data("id"); //returns myLink $('#myAnchor').data("text"); // returns hello world
Please note, while using data() function, you should not mention ‘data-‘ inside data() function. Otherwise it will not work. You need to mention the part after ‘data-‘.
var link = document.getElementById('myAnchor'); var data_id = link.getAttribute('data-id'); /
How to Fix Ambiguous Column Names in MySQL
How to List All Foreign Keys to Table in MySQL
How to Check if Row Exists in MySQL
How to Center Div Using jQuery