HTML - Global data-* Attribute



The data-* attribute is an HTML global attribute is used to form a class of attributes that define our own custom data attributes and store custom data in private on the page or application.

Following are the parts of this data attributes −

  • Attribute Name − it contains one character long, contain no capital letters and be prefixed with 'data-'.

  • Attribute Value − Can be any string.

Syntax

Following is the syntax of the data-* attribute −

<element data-id = "10784"> ...content </element >

Here "id" is optional; we can use other characters instead of id.

Example

In the following example, we are creating an HTML document and using the data-* attribute to embed custom data, as follows −

<!DOCTYPE html>
<html>
   <style>
      h1 {
         margin: 0;
      }
   
      ul {
         margin: 10px 0 0;
      }
   
      li {
         position: relative;
         width: 200px;
         padding-bottom: 10px;
      }
   
      li:after {
         content: 'Data ID: 'attr(data-id);
         position: absolute;
         top: -22px;
         left: 10px;
         background: black;
         color: white;
         padding: 2px;
         border: 1px solid #eee;
         opacity: 0;
         transition: 0.5s opacity;
      }
   
      li:hover:after {
         opacity: 1;
      }
   </style>
</head>
<body>
   <h1>Secret agents</h1>
   <ul>
      <li data-id="10784">Jason Walters, 003: Found dead in "A View to a Kill".</li>
      <li data-id="97865">Alex Trevelyan, 006: Agent turned terrorist leader; James' nemesis in "Goldeneye".</li>
      <li data-id="45732">James Bond, 007: The main man; shaken but not stirred.</li>
   </ul>
</body>undefined undefined
</html>

On runnig the above code, it will generate an output consisting of thetext in bullets format displayed on the webpage.

Example

Let's look into the another example, where we are going to use the data-* attribute to embed custom data.

<!DOCTYPE html>
<html>
<head>
   <title>data-* attribute</title>
</head>
<body>
   <h1>Organizations</h1>
   <p>Click on a organization to see what type it is:</p>
   <ul>
      <li onclick="showDetails(this)" id="tutorialspoint" data-org-type="EdTech organization">tutorialspoint</li>
      <li onclick="showDetails(this)" id="amazon" data-org-type="E-commerce organization">Amazon</li>
      <li onclick="showDetails(this)" id="google" data-org-type="It & Product Based organization">Google</li>
      <p id="type"></p>
   </ul>
   <script>
      function showDetails(org) {
         let orgType = org.getAttribute("data-org-type");
         document.getElementById("type").innerHTML = ("The " + org.innerHTML + " is a " + orgType + ".");
      }
   </script>
</body>
</html>

When we execute the above script, it will generate an output consisting of the text dispplayed in the bullet format on the webpage. when the user clicks on the amazon text it displays the embed text.

html_attributes_reference.htm
Advertisements