1

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?

Community
  • 1
  • 1
Indranil
  • 2,229
  • 2
  • 27
  • 40
  • Like for example, if you want to store an `id` to a `div`, you would put something like `data-someid="1"`, then get it using *(in JQuery)* `var someId = $("div").data('someid')` – Carl Binalla May 03 '18 at 05:45
  • So the benefit is i can put anything as an attribute name and use it in javaScript. – Indranil May 03 '18 at 07:08
  • The question I linked is somewhat old, but I think it gives a good answer. Note that the DOM API alluded to by the top answer is [dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset), which is indeed available in most browsers. – Andrew Myers May 03 '18 at 18:57

1 Answers1

0

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>
Alvin
  • 762
  • 4
  • 14