How to store custom data private to the page or application in HTML?


Custom attributes are those that are specifically designed and are not included in the standard HTML5 attributes. They enable us to customise HTML tags by adding our own data.

A custom attribute is any attribute whose name begins with data-. We can embed custom attributes on all HTML components using the data-* attributes.

Syntax: HTML

The syntax for the data-* attribute in HTML is relatively simple. Every element starting with data- is a data-* attribute.

<sample_data>
   id = “sample”
   data-index = 1
   data-row = 23
   data-column = 44
</sample_data>

Syntax: Accessing using JavaScript

Accessing these data-attributes using JavaScript is also relatively simple. We can use the getAttribute() along with their full HTML name that can be read out using the dataset property.

const article = document.querySelector('#sample');
sample_data.dataset.index;
sample_data.dataset.row;
sample_data.dataset.column;

Syntax: Accessing using CSS

The data is accessed using CSS with the help of the attr().

sample_data::before {
   content: attr(data-index);
}

Following are the examples…

Example

In the following example we read the values of the attributes using javascript.

<!DOCTYPE html> <html> <body> <h1>Result</h1> <ul> <li onclick="showPosition(this)" id="Siddarth" data-position="winner"> Siddarth </li> <li onclick="showPosition(this)" id="Arjun" data-position="runner up"> Arjun </li> <li onclick="showPosition(this)" id="Badri" data-position="third"> Badri </li> <li onclick="showPosition(this)" id="Nanda" data-position="lost"> Nanda </li> </ul> <script> function showPosition(runner) { var position = runner.getAttribute("data-position"); alert("The " + runner.innerHTML + " is " + position + "."); } </script> </body> </html>

Output

On executing the above script, it will generate an output consisting of a list of names provided with some data inside them.

When you try to click on any one of the names, the function gets the data and displays an alert showing the custom data which we have used.

Updated on: 05-Sep-2022

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements