How can I get the values of data attributes in JavaScript code?
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