How to get the data-id attribute?

How to get the data-id attribute?

I’m using the jQuery quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I’m using the .on() method to re-bind the click event for sorted items.

$(“#list li”).on(‘click’, function() {
// ret = DetailsView.GetProject($(this).attr(“#data-id”), OnComplete, OnTimeOut, OnError);


Solution 1:

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.

Solution 2:

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>

// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');
// 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 value
var fruitCount = $(this).attr('data-fruit');

// Assigning data

Read this documentation

Solution 3:

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>


$(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

Solution 4:

If you are not concerned about old IE browsers, you can also use HTML5 dataset API


<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>


var myDiv = document.querySelector('#my-div'); // "some info here"
myDiv.dataset.otherInfo // "more info here"


Full browser support list:

Solution 5:

Surprised no one mentioned:

<select id="selectVehicle">
     <option value="1" data-year="2011">Mazda</option>
     <option value="2" data-year="2015">Honda</option>
     <option value="3" data-year="2008">Mercedes</option>
     <option value="4" data-year="2005">Toyota</option>

$("#selectVehicle").change(function () {

Here is the working example:

Solution 6:


<span id="spanTest" data-value="50">test</span>





ANS : 50

Works for me!