HTML data attributes

Part of HTML5 includes the data-* attribute: a way for us to attach arbitrary data to an element. If we define a div element with a data-name="A Great Div" attribute, then our dataset property inside our node will be an object with a name key holding the string "A Great Div". For custom element-associated metadata, they are a great solution.

<div id="great" data-name="A Great Div"></div>
let div = document.getElementById("great");
console.log(div.dataset);

Play around with it. Look up the data-* attribute and explore the dataset property inside of a node. See how you can create data attributes of your own and retrieve the data they hold from the dataset object.

What happens if you have a property with a name like this?

<div id="great" data-camel-case-is-fun="i agree"></div>

Why use data attributes instead of custom attributes?

Last updated