HTML data- Attribute

 

Definition and Usage

The data- attribute is a global attribute. This attribute is new in HTML5. Means, this attribute does not work in the previous versions of HTML.
It is used to store custom data attributes on all HTML elements.

  • The value of the data- attribute can be accessed by JavaScript or CSS.
  • It’s necessary to at least one character after the prefix “data-“.
  • The data- attribute value should be string.
  • The data- attribute name should not contain on any uppercase letters.

Example :

<h3>Click on a phrase to see, who wrote this phrase?</h3>

<ul>
<li onclick="authorName(this)" data-phrase-by="Asim">Walking in the rain can be difficult.</li>
<li onclick="authorName(this)" data-phrase-by="Salman">Getting a promotion is exciting.</li>
<li onclick="authorName(this)" data-phrase-by="Irfan">Going for walk is a real treat.</li>
</ul>

<script>

function authorName(author) {
alert("This phrase is written by " + author.getAttribute("data-phrase-by") + ".");
}

</script>
Result

Click on a phrase to see, who wrote this phrase?

  • Walking in the rain can be difficult.
  • Getting a promotion is exciting.
  • Going for walk is a real treat.

 

Here are a few tutorials for you to read next:

If you find this tutorial helpful, then please Subscribe to our YouTube Channel for video tutorials, and share this article on social media.

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes0
No0
Powered by Helpful

Leave a Comment

Your email address will not be published. Required fields are marked *