June 8, 2026

Datasets in Html and Javascript

This is a sample to show how to use datasets to put data into the html and how to access it

<button data-sandwich="tuna" data-topping="tomato" data-snack="cookies">Place Order</button>
Here is the Javascript to access the dataset on the button:

let btn = document.querySelector('button');

let dataset = btn.dataset; // Access "data-" attributes here
console.log("All dataset attributes: ");
console.log(dataset); 

let sandwich = btn.dataset.sandwich; // Access individually as properties of "dataset"
console.log("sandwich=" + sandwich);

let {topping, snack} = btn.dataset; // Access using tuples
console.log(sandwich, topping, snack);

let snack2 = btn.dataset["snack"]; // Access the properties dynamically
console.log("snack2=" + snack);

btn.dataset.side = 'chips'; // Add more dataset attributes
console.log(dataset); 
 
console.log("All done"); 
The code can be accessed here: https://codepen.io/capitanacerimmer/pen/JobbWYa?editors=1111
Note that the console output is not activated by the button

No comments: