admin管理员组文章数量:1323330
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
本文标签: javascriptHTML store value into div and get its valueStack Overflow
版权声明:本文标题:javascript - HTML store value into div and get its value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742139482a2422517.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论