Why use data star (data-*) attribute in html5?

1.5k Views Asked by At

I was going through HTML5 and I found data-* attribute is new to HTML5. But I didn't understand its importance. As per its definition from w3schools I understood:

  • The data-* attributes is used to store custom data private to the page or application.

Question: What does it mean by custom data? How we can use data-* to store custom data?

  • The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.

The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

Question: We already can add attributes to an element and use it in JavaScript, then why use data-* attribute?

1

There are 1 best solutions below

0
On

You can use data-* for better and most flexible organization. A practical example would be something like that:

$("#result").text( $("#player").data("age") + " years old, " +
"Actual Team: "+$("#player").data("team") );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

</script>
<!-- For Example, multiple data in a single div-->
<div data-age="33" data-team="Real Madrid" id="player">
       Cristiano Ronaldo profile: <span id="result"></span>
</div>