Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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