1027

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);
  alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

<ul id="list" class="grid">
  <li data-id="id-40" class="win">
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
    </a>
  </li>
</ul>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bruce Adams
  • 12,040
  • 6
  • 28
  • 37

17 Answers17

1996

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.

Kaushik Thanki
  • 3,334
  • 3
  • 23
  • 50
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
  • 72
    This is returning 'undefined' for me. – Foreever Apr 25 '14 at 14:28
  • 141
    For those who report it doesn't work, make sure your attribute contains only lower case letters. For example "data-listId" should be "data-listid". See http://stackoverflow.com/questions/10992984/jquery-data-returns-undefined-attr-returns-integer for the reason why. – WindChimes Nov 23 '14 at 04:42
  • Thanks for mentioning the lowercase part... After 8 years this helped me. I was making the same camel casing mistake. – Shreyansh Kashyap Jan 25 '22 at 17:17
  • There's a major difference between using these two methods. If you use .attr, then you get the latest updated value of data-id if it was updated. But using .data won't get you the latest value. – Leutecia Jan 30 '23 at 14:16
212

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 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
</script>

Through jQuery

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

// Assigning data
$(this).attr('data-fruit','7');

Read this documentation

Lalit Kumar Maurya
  • 5,475
  • 2
  • 35
  • 29
  • Due to very good [support of the dataset API](https://caniuse.com/mdn-api_htmlelement_dataset), the JavaScript part should be considered obsolete. – Andy Jul 20 '22 at 12:41
121

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Serge Shultz
  • 5,888
  • 3
  • 27
  • 17
72

If you are not concerned about old Internet Explorer browsers, you can also use HTML5 dataset API.

HTML

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

JavaScript

var myDiv = document.querySelector('#my-div');

myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"

Demo: http://html5demos.com/dataset

Full browser support list: http://caniuse.com/#feat=dataset

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roni
  • 3,308
  • 3
  • 21
  • 27
31

You can also use:

<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>
</select>

$("#selectVehicle").change(function () {
    alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
curiousBoy
  • 6,334
  • 5
  • 48
  • 56
31

This piece of code will return the value of the data attributes. For example: data-id, data-time, data-name, etc.

I have shown it for the id:

<a href="#" id="click-demo" data-id="a1">Click</a>

JavaScript: Get the value of the data-id -> a1

$(this).data("id");

JQuery: This will change the data-id -> a2

$(this).data("id", "a2");

JQuery: Get the value of the data-id -> a2

$(this).data("id");
Jiří
  • 415
  • 6
  • 16
Ashok
  • 800
  • 11
  • 20
15

HTML

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

JavaScript

$(this).data().value;

or

$("span#spanTest").data().value;

ANS: 50

Zoe
  • 27,060
  • 21
  • 118
  • 148
bamossza
  • 3,676
  • 1
  • 29
  • 28
14

Accessing the data attribute with its own id is a bit easy for me.

$("#Id").data("attribute");

function myFunction(){
  alert($("#button1").data("sample-id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aravindh Gopi
  • 2,083
  • 28
  • 36
12

I use $.data:

//Set value 7 to data-id
$.data(this, 'id', 7);

//Get value from data-id
alert( $(this).data("id") ); // => outputs 7
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gjermund Dahl
  • 1,410
  • 17
  • 25
12
var id = $(this).dataset.id

works for me!

ofir_aghai
  • 3,017
  • 1
  • 37
  • 43
6

Using jQuery:

$(".myClass").load(function() {
  var myId = $(this).data("id");
  $('.myClass').attr('id', myId);
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

Try

this.dataset.id

$("#list li").on('click', function() {
  alert( this.dataset.id );
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

<ul id="list" class="grid">
  <li data-id="id-40" class="win">
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />
    </a>
  </li>
</ul>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
4

for pure js

 let btn = document.querySelector('.your-btn-class');
 btn.addEventListener('click',function(){
 console.log(this.getAttribute('data-id'));
 })
  • While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Luca Kiebel Jan 07 '22 at 12:27
2

The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.

$('#select').on('change', function(){
        let element = $("#visiabletoID");
        element.val($(this).find(':selected').data('record'));
    });
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
0

For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See .tooltip('dispose').

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ben
  • 2,957
  • 2
  • 27
  • 55
0

HTML 5 introduced dataset: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset, the browser compa But for older browser you can use getAttribute method to get the data-* attributes.

const getDataAttr = (id) => {
  if(currentNode.dataset) return currentNode.dataset[id];
  return currentNode.getAttribute("data-"+id);
}

The reason to use dataset is constant lookup time, get attribute would not be a constant time lookup, it'll go through all the attributes of the html element and then return the data once it'll find the exact attribute match.

The reason to provide this answer is that nobody mentioned about the browser compatibility and lookup time with the given solution, although both of these solutions are already given by people.

Prashant Pandey
  • 139
  • 1
  • 7
-2

I have a span. I want to take the value of attribute data-txt-lang, which is used defined.

$(document).ready(function ()
{
    <span class="txt-lang-btn" data-txt-lang="en">EN</span>
    alert($('.txt-lang-btn').attr('data-txt-lang'));
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pergin Sheni
  • 393
  • 2
  • 11