HTML Custom data-* Attribute Tutorial

In this section, we will learn what the data-* attribute is and how to use it in HTML.

HTML Custom Attributes: HTML data-* Attribute Definition and Usage

HTML elements have attributes, as you saw throughout these tutorials. Each of these attributes has a specific purpose. For example, one is used for identifying an element (the `id` attribute), another one for changing the style of an element (the style attribute) and so many others that do something on an element.

But in rare cases, we might need an attribute that none of these built-in attributes could handle such a task.

So what should we do then? Well, HTML creators thought about this, and they came up with custom attributes!

A custom attribute is basically an attribute that we create ourselves and assign values to them.

These custom attributes help us to embed data into HTML elements and then, with the help of programming languages like JavaScript, we can access those embedded data and apply the desired changes.

In order to create a custom attribute in HTML, we use this syntax:

data-*

The asterisk here is replaced with the name of the custom attribute that we want to create.

For example, if the name of the custom attribute is “finance”, the custom attribute would be `data-finance`.

Also, just like other attributes, we can assign values to custom attributes as well.

For example:

<element data-finance = “$1000”>

Basically, depending on the need of the program, we set the necessary data for the target custom attribute.

Note: browsers ignore any custom attribute created via `data-*`.

HTML data-* Attribute Syntax

<element data-* = “value”>

Example: using data-* attribute in HTML

See the Pen using data-* attribute in HTML by Omid Dehghan (@odchan1) on CodePen.

Leave a Reply