Skip to content

Instantly share code, notes, and snippets.

@jwheare
Last active December 16, 2015 01:19
Show Gist options
  • Save jwheare/5354105 to your computer and use it in GitHub Desktop.
Save jwheare/5354105 to your computer and use it in GitHub Desktop.
jQuery's dataAttr function for parsing data-attrs to js types
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment