Skip to content

Instantly share code, notes, and snippets.

@draeton
Created February 28, 2012 02:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save draeton/1928836 to your computer and use it in GitHub Desktop.
Save draeton/1928836 to your computer and use it in GitHub Desktop.
Get HTML5 data attributes with no type coercion
/**
* jQuery.readDataAttr
*
* Gets html5 data attributes without type coercion.
* If called with no parameters, returns an object with all
* current data-* values.
*
* @param {String} [key] Optional; if set, return only this
* value
* @return {*} Return either all values, or the value at key
*/
(function (window, $) {
"use strict";
var slice = Array.prototype.slice;
var cache = {};
var uuid = 0;
var expando = "jQueryReadDataAttr" + (+new Date());
var dataTest = /^data-/;
var readDataAttr = function (elem) {
var id = elem[expando];
var data = cache[id];
var attrs, attr, i, l, key;
if (!$.isPlainObject(data)) {
attrs = slice.call(elem.attributes);
data = {};
for (i = 0, l = attrs.length; i < l; i++) {
attr = attrs[i];
if (dataTest.test(attr.name)) {
key = attr.name.replace(dataTest, "");
key = $.camelCase(key);
data[key] = attr.nodeValue;
}
}
id = uuid++;
cache[id] = data;
elem[expando] = id;
}
return data;
};
$.fn.readDataAttr = function (key) {
var elem = $(this).get(0);
var data = readDataAttr(elem);
if (typeof key !== "undefined") {
key = $.camelCase(key);
data = data[key];
}
return data;
};
$.readDataAttr = function (elem, key) {
return $(elem).readDataAttr(key);
};
}(window, jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment