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
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
Share edited Sep 1, 2016 at 11:20 Shashank Agrawal 25.8k11 gold badges96 silver badges125 bronze badges asked Sep 1, 2016 at 8:56 varadvarad 8,04921 gold badges67 silver badges114 bronze badges 1- Possible duplicate of How to get the data-id attribute? – Shashank Agrawal Commented Sep 1, 2016 at 10:39
5 Answers
Reset to default 2Use .attr()
or .getAttribute()
. That would work.
jQuery Solution
$(function(){
console.log($('#first').attr('data-value'));
});
<script src="https://ajax.googleapis./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>
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 HTML5data-*
attribute.
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");
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"
Use the getAttribute() method.
In your case -
document.getElementById('first').getAttribute('data-value')
Documentation can be found here: http://www.w3schools./jsref/met_element_getattribute.asp