Custom Data Attributes

Custom data attributes allow for data to be exchanged between HTML and JavaScript in a structured way.

data-*

All custom data attributes start with data- followed by a custom name. From there, they act as any other HTML attribute and can be used to store data inside an HTML tag.

<img data-large="cat-2400.jpg" data-source="Image by Dimitri Houtteman from Pixabay" alt="A kitten playing with a flower" src="cat-300.jpg">

Dataset

The dataset property is used to access any custom data attributes of an HTML element. The custom names become properties of dataset with the kebab-case being converted to camel-case Example: data-test-value will be accessible using dataset.testValue.

const $img = document.querySelector('img')
console.log($img.dataset.large) // cat-2400.jpg

Usage

Custom data attributes can be used to store data in HTML that can then be accessed and used by JavaScript. The following example demonstrates how the custom data attributes can be used to display a larger version of an image.