Comment

Dominic Watson

Or, indeed, a somewhat tidier version:

$.fn.getData( function( attr ){
 return this.attr( 'data-' + attr ) || this.data( attr );
} );

Parent comment

Peter Bengtsson

Check what Jurriaan wrote above. There are risks with reading with .data()

Replies

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!