varad
varad

Reputation: 8029

HTML store value into div and get its value

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

Upvotes: 4

Views: 11551

Answers (5)

Matthew Steele
Matthew Steele

Reputation: 1

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"

Upvotes: 0

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

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.

Upvotes: 1

Nick Pierpoint
Nick Pierpoint

Reputation: 17769

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

Upvotes: 0

Hitesh Misro
Hitesh Misro

Reputation: 3461

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>

Upvotes: 2

Nitzo
Nitzo

Reputation: 79

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

Upvotes: -1

Related Questions