How to get data attributes using jquery .data()
? In which case html5 data-*
attributes converts to lowercase and camelcase? What are all the main rules to follow while using custom attributes to store data?
<input type="button" class="myButton" value="click me" data-productId="abc"/>
<input type="button" class="myButton" value="click me" data-product-id="abc"/>
<input type="button" class="myButton" value="click me" data-PRODUCT-ID="abc"/>
<input type="button" class="myButton" value="click me" data-ProDUctId="abc"/>
HTML5 allows us to create our own custom attributes to store data. Custom attributes can be called anything we like, like variable names, but they need to be prepended with the word 'data', and words are separated by dashes. You could add "foo", "bar", and "foo bar" data attributes to an input like this:
jQuery's
.data()
method will give you access todata-*
attributes.Using jQuery up to and including version 1.4, data attributes were case insensitive, therefore:
would be accessible with
jQuery 1.5 and 1.6
However, changes in jQuery 1.5 and 1.6 mean that data attributes are now forced to lowercase, so:
is only accessible with
Any
data-*
attributes become properties of the element’s dataset object. The new property names are derived as follows:data-
prefix is stripped from the attribute name.Notice that the original attribute name
data-product-id
has been converted toproductId
in the dataset object. The name conversion process must be accounted for when namingdata-*
attributes. Since the attribute names are converted to lowercase, it is best to avoid using uppercase letters. The following example shows how several attribute names translate to dataset properties.NOTE:
alt
attribute is a better choice.data-*
attributes should not be used by third party applications. This means that programs such as search engines should not rely on custom data attributes when preparing search results.Implementing custom attributes in HTML5 is not technically complex in itself, however the real difficulty is in choosing whether it is appropriate to use them in your own projects, and if so how to go about it efficiently. Finally, do remember that it’s still a little early to start using the dataset approach for functions your pages rely on, so be sure to provide an alternative for non-supporting browsers.
DEMO