Advanced

HTML Data Attributes

Using Data Attributes

HTML data attributes store custom data, accessible via JavaScript.

Introduction to HTML Data Attributes

HTML data attributes are custom attributes that allow you to store additional data on HTML elements. They are ideal for providing extra information that can be accessed and manipulated using JavaScript. Data attributes are particularly useful when you want to pass information from your HTML to your JavaScript code without using IDs or classes.

Syntax of Data Attributes

The syntax for data attributes is straightforward. They are prefixed with data- followed by a custom name. The attribute value is a string, which can represent any data type when accessed via JavaScript.

Accessing Data Attributes with JavaScript

You can access data attributes in JavaScript using the dataset property of an HTML element. The dataset property returns a DOMStringMap that allows you to read and write custom data attributes.