How do we embed custom data attributes on all HTML elements?



In this article, we need to embed custom data attributes on all HTML elements. we can do so, using the data-* attribute in HTML.

The data-* attribute in HTML is used to custom data private to the webpage or application. This attribute adds custom values to an HTML element.

The data-* attribute in HTML consists of two parts −

  • The attribute value can be any string.

  • The attribute name should only contain lowercase letters and must have at least one character after the prefix "data-".

This data is commonly used in JavaScript to improve the user experience. Following are the examples, where embed custom data attributes on HTML element.

Example 1

In this example,

  • We have listed three (clothing’s) with custom data-id and data-price data attached

  • Here, the data attributes are not visible to the users.

  • Though the values cannot be seen by the users, values will be present in the document.

<!DOCTYPE html> <html> <head> <title>How do we embed custom data attributes on all HTML elements? </title> </head> <body> <ul> <li data-id="1" data-price="INR 1899">Shirt</li> <li data-id="2" data-price="INR 2799">Pant</li> <li data-id="3" data-price="INR 4599">Jacket</li> </ul> </body> </html>

The values are not displaying because we are not extracting the custom attributes which we specified.

Example 2

In the example,

  • We’ve created four links with tags inside the HTML table.

  • Each element has a custom data-plyr-type attribute with a player name.

  • We’ve used onClick event to extract the custom attributes.

  • Whenever we clicked on the elements, the JavaScript function extracts and displays the player’s country name.

<!DOCTYPE html> <html> <head> <script> function showData(plyr) { var players = plyr.getAttribute("data-plyr-type"); alert(plyr.innerHTML + " is a " + players + "."); } </script> </head> <body> <h1>Cricketers!</h1> <p>Click on a player to see which team he belongs to:</p> <table border=2 px;> <caption>Players</caption> <tr> <td onclick="showData(this)" id="owl" data-plyr-type="Afganistan player">Rashid khan</td> <td onclick="showData(this)" id="owl" data-plyr-type="Pakistan player">Babar azam</td> </tr> <tr> <td onclick="showData(this)" id="salmon" data-plyr-type="England player">Jos Buttler</td> <td onclick="showData(this)" id="salmon" data-plyr-type="Australia player">Steve smith</td> </tr> <tr> <td onclick="showData(this)" id="tarantula" data-plyr-type="India player">Jasprit bumrah</td> <td onclick="showData(this)" id="tarantula" data-plyr-type="West indies player">Jason holder</td> </tr> </table> </body> </html>

As we can see in the output, when the user clicks on any cricketer’s table data, the custom attribute will get extracted and displays the particular player’s country name.


Advertisements