How can I retrieve the values of data attributes in JavaScript?

How can I retrieve the values of data attributes in JavaScript?

I have the following HTML:

<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

Is it possible to access the attributes that start with data- and use them in my JavaScript code as shown below?

Currently, I’m getting null as a 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"
});
});

Can you provide guidance on how to effectively use JavaScript get data attribute?

You can access data attributes using the dataset property, which allows you to reference data attributes directly by their names, converted to camelCase.

document.getElementById("the-span").addEventListener("click", function() {
var json = JSON.stringify({
id: parseInt(this.dataset.typeid), // Use camelCase
subject: this.dataset.type, // Use camelCase
points: parseInt(this.dataset.points), // Use camelCase
user: "H. Pauwelyn"
});
console.log(json);
});

Alternatively, you can use the getAttribute method to retrieve data attributes by their exact names.

document.getElementById("the-span").addEventListener("click", function() {
var json = JSON.stringify({
id: parseInt(this.getAttribute("data-typeId")),
subject: this.getAttribute("data-type"),
points: parseInt(this.getAttribute("data-points")),
user: "H. Pauwelyn"
});
console.log(json);
});

If you want to retrieve all data attributes dynamically, you can iterate over the dataset property.

document.getElementById("the-span").addEventListener("click", function() {
const attributes = this.dataset;
let obj = { user: "H. Pauwelyn" };
for (let key in attributes) {
obj[key] = attributes[key];
}
obj.id = parseInt(attributes.typeid); // Add id separately if needed
var json = JSON.stringify(obj);
console.log(json);
});