How can I get the data-id attribute? How can I get the data-id attribute? javascript javascript

How can I get the data-id attribute?


To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use

$(this).attr("data-id") // will return the string "123"

or .data() (if you use newer jQuery >= 1.4.3)

$(this).data("id") // will return the number 123

and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.


If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

Through JavaScript

<div id='strawberry-plant' data-fruit='12'></div><script>// 'Getting' data-attributes using getAttributevar plant = document.getElementById('strawberry-plant');var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'// 'Setting' data-attributes using setAttributeplant.setAttribute('data-fruit','7'); // Pesky birds</script>

Through jQuery

// Fetching datavar fruitCount = $(this).data('fruit');OR // If you updated the value, you will need to use below code to fetch new value // otherwise above gives the old value which is intially set.// And also above does not work in ***Firefox***, so use below code to fetch valuevar fruitCount = $(this).attr('data-fruit');// Assigning data$(this).attr('data-fruit','7');

Read this documentation


Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will not be reflected in the data() jQuery function. You have to adjust it via data() function as well.

<a data-id="123">link</a>

JavaScript:

$(this).data("id") // returns 123$(this).attr("data-id", "321"); //change the attribute$(this).data("id") // STILL returns 123!!!$(this).data("id", "321")$(this).data("id") // NOW we have 321