Get list of data-* attributes using javascript / jQuery

Actually, if you’re working with jQuery, as of version 1.4.3 1.4.4 (because of the bug as mentioned in the comments below), data-* attributes are supported through .data():

As of jQuery 1.4.3 HTML 5 data-
attributes will be automatically
pulled in to jQuery’s data object.

Note that strings are left intact
while JavaScript values are converted
to their associated value (this
includes booleans, numbers, objects,
arrays, and null). The data-
attributes are pulled in the first
time the data property is accessed and
then are no longer accessed or mutated
(all data values are then stored
internally in jQuery).

The jQuery.fn.data function will return all of the data- attribute inside an object as key-value pairs, with the key being the part of the attribute name after data- and the value being the value of that attribute after being converted following the rules stated above.

I’ve also created a simple demo if that doesn’t convince you: http://jsfiddle.net/yijiang/WVfSg/

Leave a Comment