I have next html:
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
Is it possible to get the attributes that beginning with data-, and use it in the JavaScript code like code below? For now I get null as result.
document.getElementById("the-span").addEventListener("click", function(){
var json = JSON.stringify({
id: parseInt(this.typeId),
subject: this.datatype,
points: parseInt(this.points),
user: "H. Pauwelyn"
});
});
You need to access the dataset property:
document.getElementById("the-span").addEventListener("click", function() {
var json = JSON.stringify({
id: parseInt(this.dataset.typeid),
subject: this.dataset.type,
points: parseInt(this.dataset.points),
user: "Luïs"
});
});
Result:
// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }
Because the dataset property wasn't supported by Internet Explorer until version 11, you may want to use getAttribute() instead:
document.getElementById("the-span").addEventListener("click", function(){
console.log(this.getAttribute('data-type'));
});
You can access it as
element.dataset.points
etc. So in this case: this.dataset.points
if you are targeting data attribute in Html element,
document.dataset will not work
you should use
document.querySelector("html").dataset.pbUserId
or
document.getElementsByTagName("html")[0].dataset.pbUserId
Akash Agrawal
Try this instead of your code:
var type=$("#the-span").attr("data-type");
alert(type);
来源:https://stackoverflow.com/questions/33760520/get-data-attributes-in-javascript-code