Comment

Bane Georgievski

If your data attr held a json object you might want to check first.

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return str;
    }
    return JSON.parse(str);
}

$.fn.getDataAttr = function( attr ){
 if ( this.attr( 'data-' + attr ) ) {
   return isJson(this.attr( 'data-' + attr ));
 }
 return this.data( attr );
};

These 2 functions will ensure that you get the data back properly .
Live long and prosper!

Parent comment

Dominic Watson

Or, indeed, a somewhat tidier version: $.fn.getData( function( attr ){ return this.attr( 'data-' + attr ) || this.data( attr ); } );