Morais
Morais

Reputation: 801

Retrieving HTML data-attributes using jQuery

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" >

Upvotes: 47

Views: 82022

Answers (5)

Inba Krish
Inba Krish

Reputation: 21

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" >

Upvotes: 1

Alytrem
Alytrem

Reputation: 2620

Use the jQuery .data() function:

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

Upvotes: 157

<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");

Upvotes: 1

Frederiek
Frederiek

Reputation: 1613

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 />");

});

Upvotes: 11

Marcus Blomberg
Marcus Blomberg

Reputation: 473

You should be able to use the .attr function:

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

Upvotes: 20

Related Questions