4

I have a div like

<div class="firstclass" id="first" data-value="firstvalue">SomeThing</div>

Here I want to get the value in data-value like by doing document.getElementById('first').value or something like this..

How can I get this value or if there is similar approach

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
varad
  • 7,309
  • 20
  • 60
  • 112
  • Possible duplicate of [How to get the data-id attribute?](http://stackoverflow.com/questions/5309926/how-to-get-the-data-id-attribute) – Shashank Agrawal Sep 01 '16 at 10:39

5 Answers5

2

Use .attr() or .getAttribute(). That would work.

jQuery Solution

$(function(){
  console.log($('#first').attr('data-value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="firstclass" id="first" data-value="firstvalue">SomeThing</div>

JavaScript Solution

function Example(){
  console.log(document.getElementById('first').getAttribute("data-value")); 
}
Example();
<div class="firstclass" id="first" data-value="firstvalue">SomeThing</div>
Hitesh Misro
  • 3,397
  • 1
  • 21
  • 50
1

jQuery has the data() method. Consider using it:

// To get/read the value
$("#first").data("value")
// To set the value
$("#first").data("value", "foo-bar")

Docs:

Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
0

You can consider it as a normal attribute and use plain javascript as follows:

document.getElementById("first").getAttribute('data-value');

Since the attribute naming follows the data- naming convention we can use the HTML5 data specification.

In plain javascript you use the dataset API:

document.getElementById("first").dataset.value;

However, jQuery provides a nice shortcut for this:

$("#first").data("value");
Nick Pierpoint
  • 17,641
  • 9
  • 46
  • 74
0

I have found that using .val() works nicely here

To Set: $("#div").val(1); // Sets value of div to 1

To Retrieve: let foo = $("#div").val(); // Retrieves "1"

-1

Use the getAttribute() method.

In your case -

document.getElementById('first').getAttribute('data-value')

Documentation can be found here: http://www.w3schools.com/jsref/met_element_getattribute.asp

Nitzo
  • 79
  • 6