0

I've seen some data accessed in a javascript function like this:

$(this).data('js');

In the html, the data is assigned like this.

<li data-js="m">
    <a href="#">Male</a>
</li>
<li data-js="f">
    <a href="#">Female</a>
</li>

I've just not seen this done before. And I don't really know what to call it to search for it. Inline jquery data assignment? Is it good practice? Well supported? What's it called? Thanks!

1252748
  • 14,597
  • 32
  • 109
  • 229
  • 2
    They're called `data` attributes. They are part of the HTML5 specification. – Rory McCrossan Jan 30 '13 at 22:44
  • This is what you need [http://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes](http://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) – elclanrs Jan 30 '13 at 22:48
  • @thomas The end of using `rel` and `class` attributes to handle data are over! Now we can use `data` attributes to store data related to elements. – kyle.stearns Jan 30 '13 at 22:57

3 Answers3

2

This is a simple jQuery method that takes advantage of HTML5 Custom Data Attribute feature:

A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters. Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

In your example, the $(this).data('js'); code will either return "m" or "f" depending on whether this refers to the first or second li.

Here are some relevant articles:

Joey
  • 1,651
  • 15
  • 30
1

the jQuery function is documented here http://api.jquery.com/jQuery.data/

and this has a good explanation of the html5 data attribute http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/all-you-need-to-know-about-the-html5-data-attribute/

Decker W Brower
  • 931
  • 6
  • 16
-1

Have you read the jQuery documentation? I think that will give you enough information on its usage and purpose http://api.jquery.com/jQuery.data/

thaJeztah
  • 27,738
  • 9
  • 73
  • 92