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!
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.
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!