Using Dataset in JavaScript

Catherine Jimenez
2 min readSep 6, 2020

Dataset. What is it? Why use it? It can be a bit confusing initially, but once you get the hang of things, dataset is an excellent tool for setting and accessing information within the DOM!

A common reaction amongst those hearing about dataset for the first time.

Dataset is a property used on HTML elements in JavaScript. Essentially, it provides you with a way to store data on the DOM and allows you to set and get data values from your HTML elements.

For instance, if you wanted to make sure you could access values set inside of a specific scope, you could assign data attributes to an element to ensure the data would be stored on the DOM. Overall, a nifty way to make sure you’ll be able to access the data directly from the DOM should you need to retrieve it from outside the scope in which it was defined.

Assigning the data is simple and can be done using the following format: element.dataset.variable = value you want to assign.

For instance, if you wanted to add attributes (an id, a name, and an image) to a span element using dataset, you could do so as follows:

In this case, we are assigning data values using information derived from the pup object being passed into the renderPup function. If you were to console.log (pupSpan), the pup span will appear on the console with all of the data attributes assigned to it.

Our updated pupSpan!

In order to access the values saved in your dataset, you can call them wherever you need them in your code later on.

In the above example, we are able to take the predefined dataset values and assign them to variables within the scope of an entirely different function or event handler. Inside the renderPup function, we used dataset to assign values that we are now using to set variables inside an event listener.

Had we not used dataset, we would only have access to those specific values within of the scope of the initial function in which they are defined. However, that becomes a non-issue when using dataset.

Good luck out there, you expert-DOM-manipulator-in-training, you!

Me, after FINALLY figuring out how to correctly use dataset.



Catherine Jimenez

Latina Software Engineer | Ravenclaw rising | cat lady