47

How can I get the values stored in the data attributes using jQuery ?

<div class="sm-tot" data-ts-speed="500" data-ts-interval="4000" data-ts-newVal="5000" >
3
  • 2
    What have you tried? What was the expected result? What was the actual result? Did you get any error messages? Commented Mar 15, 2012 at 13:33
  • see this : stackoverflow.com/questions/2048720/… Commented Mar 15, 2012 at 13:38
  • 3
    @Morais, you should check Alytrem's answer as correct. Commented May 24, 2013 at 14:26

5 Answers 5

157

Use the jQuery .data() function:

var speed = $("yourdiv").data("ts-speed");
Sign up to request clarification or add additional context in comments.

4 Comments

this from jQuery 1.4.3 - on one project i have 1.4.2 =)
this one doesn't work for me. The answer below, use attr instead of data works for me.
@Morais last seen May 18, 2016 and still no check for the right answer.
Maybe it didn't work for @Carrie because of older version. It works perfectly with jQuery 3.2.1.
20

You should be able to use the .attr function:

var speed = $("yourdiv").attr("data-ts-speed");

Comments

11

this shoud give you a idea how

html:

<div class="sm-tot" data-ts-speed="500" data-ts-interval="4000" data-ts-newVal="5000" > </div>

js:

$(document).ready(function(){
    var speed = $("div.sm-tot").data("ts-speed");
    var interval = $("div.sm-tot").data("ts-interval");
    $("div.sm-tot").append("speed: " + speed + "<br />");
    $("div.sm-tot").append("interval: " + interval + "<br />");

});

Comments

1
<div class="sm-tot" data-ts-speed="500" data-ts-interval="4000" data-ts-newVal="5000" >

well, for this div u can get someone attr with jquery using code like this first follow this pattern

   if is Class $(".ClassName").attr('AttrName');
   if is Id  $('#IDname').attr('attrName')

if u wan get "data-ts-interval" u will use $('.sm-tot').attr("data-ts-interval");

Comments

1

For getting data attributes using JQuery, you can make use of the attributes function (.attr()) and get the value of the required data attribute

let value = $(".sm-tot").attr("data-ts-speed"); // here you have the attr() method which gets the attribute value for only the first element in the matched set.

console.log(value); // here is the logged value of your class element
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="sm-tot" data-ts-speed="500" data-ts-interval="4000" data-ts-newVal="5000" >

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.