HTML | data-* Attributes

Custom Data Attributes allow you to add your own information to tags in HTML. Even though the name suggests otherwise, these are not specific to HTML5 and you can use the data-* attribute on all HTML elements.

The data-* attributes can be used to define our own custom data attributes. It is used to store custom data in private to the page or application.

There are mainly 2 parts of the Data Attributes:



  1. Attribute Name: Must be at least one character long, contain no capital letters and be prefixed with ‘data-‘.
  2. Attribute Value: Can be any string.

Syntax:

<li data-book-author="Rabindra Nath Tagore"> Gitanjali </li>

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<head>
    <script>
        function showDetails(book) {
            var bookauthor = book.getAttribute("data-book-author");
            alert(book.innerHTML + " 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)" id="gitanjali" 
                data-book-author="Rabindra Nath Tagore">
            Gitanjali
        </li>
          
        <li onclick="showDetails(this)" id="conquest_of_self" 
                data-book-author="Mahatma Gandhi">
            Conquest of Self
        </li
         
        <li onclick="showDetails(this)" id="broken_wings" 
                data-book-author="Sarojini Naidu">
            Broken Wings
        </li
    </ul>
</body>
</html>                    

chevron_right


Output:

When we click on the book, we can see the name of the author in a separate dialogue box.

Supported Browsers: The browser supported by title attribute are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Safari
  • Opera


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.