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" >
informatik01
  • 16,038
  • 10
  • 74
  • 104
Morais
  • 801
  • 2
  • 10
  • 15

5 Answers5

157

Use the jQuery .data() function:

var speed = $("yourdiv").data("ts-speed");
Ethan
  • 4,295
  • 4
  • 25
  • 44
Alytrem
  • 2,620
  • 1
  • 12
  • 13
20

You should be able to use the .attr function:

var speed = $("yourdiv").attr("data-ts-speed");
Marcus Blomberg
  • 473
  • 2
  • 6
  • 10
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 />");

});
Frederiek
  • 1,605
  • 2
  • 17
  • 32
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");

0

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" >
depperm
  • 10,606
  • 4
  • 43
  • 67
Inba Krish
  • 11
  • 3