HTML data-* Attributes
The HTML data-* attribute allows storing custom data for elements, enhancing interactivity in web applications through JavaScript without server-side involvement or AJAX calls.
Syntax
<li data-book-author="Rabindra Nath Tagore"> Gitanjali </li>
The data-* attributes can be used to define our own custom data attributes. It stores custom data in private to the page or application.
There are mainly 2 parts of the Data Attributes:
- Attribute Name: Must be at least one character long, contain no capital letters, and be prefixed with ‘data-‘.
- Attribute Value: Can be any string.
HTML data-* Attributes Examples
Example1: In this example HTML data-* attributes (e.g., data-book-author) store custom data directly in elements, enabling JavaScript to access and utilize this data, as demonstrated in the example for displaying book authors.
HTML
<!DOCTYPE html> < html > < head > < script > function showDetails(book) { let bookauthor = book.dataset.bookAuthor; alert( book.textContent + " is written by " + bookauthor + "." ); } </ script > </ head > < body > < h1 >Books</ h1 > < p > Click on the book name to know author's name : </ p > < ul > < li onclick = "showDetails(this)" data-book-author = "Rabindra Nath Tagore" > Gitanjali </ li > < li onclick = "showDetails(this)" data-book-author = "Mahatma Gandhi" > Conquest of Self </ li > < li onclick = "showDetails(this)" data-book-author = "Sarojini Naidu" > Broken Wings </ li > </ ul > </ body > </ html > |
Output:
Example 2: In this example HTML data-* Attributes (e.g., data-director-name, data-released-year) store custom data within HTML elements, accessed by JavaScript for dynamic content display without affecting rendering.
HTML
<!DOCTYPE html> < html > < head > < script > function showDetails(movie) { let directorName = movie.getAttribute( "data-director-name" ); let releaseYear = movie.getAttribute( "data-released-year" ); alert(`${movie.textContent} is released at ${releaseYear} and directed by ${directorName}.`); } </ script > </ head > < body > < h1 >Movies</ h1 > < ul > < li onclick = "showDetails(this)" data-director-name = "Christopher Nolan" data-released-year = "2008" > The Dark Knight </ li > < li onclick = "showDetails(this)" data-director-name = "Christopher Nolan" data-released-year = "2010" > Inception </ li > < li onclick = "showDetails(this)" data-director-name = "James Cameron" data-released-year = "2009" > Avatar </ li > </ ul > </ body > </ html > |
Output:
Supported Browsers: The browser supported by HTML data-* Attribute are listed below:
Contact Us