WDD 330: Web Frontend Development II

W05 Learning Activity: Dataset

Overview

The dataset HTML property is a way to access custom data attributes on HTML elements. This allows for the storage of additional information on an element without affecting the HTML structure. The dataset property is an object that contains all the custom data attributes of an element, and each attribute can be accessed using camelCase notation. For example, if an element has a data attribute of data-user-id, it can be accessed using element.dataset.userId.

Prepare

dataset is a property on any HTML element that allows you to access custom data-* attributes. This allows data to be passed to JavaScript without using id or class attributes, which can become extensive and complex. Using dataset prepares you to used many UI frameworks that use data attributes to bind data to HTML elements, keeping things flexible and declarative in HTML.

Here is an example of how to use the dataset property:

<button data-user-id="42" data-role="admin">Edit</button>
const element = document.querySelector('#myElement');
element.dataset.userId = '12345';
console.log(element.dataset.userId); // '12345'
element.dataset.userId = '67890';
console.log(element.dataset.userId); // '67890'
element.dataset.userId = '12345';
console.log(element.dataset.userId); // '12345'
element.dataset.userId = '67890';
console.log(element.dataset.userId); // '67890'

Activity Instructions

Optional Resources