Comment

Dominic Watson

Yes, the real risk is using attr('data-foo') to read the data. Better to always use .data('foo') to read it.

Replies

Peter Bengtsson

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

Dominic Watson

That's depressing (the comment was not visible when I posted). Good to know though. You might want to wrap the logic in your own getData() method should you really never want to directly expect that there is an html attribute. Something along the lines of (untested):

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

 return this.data( attr );
} );

This way, data could be set on the element as either an attribute or using .data() and you run no risk of expecting either one when you want to read the data back.

Dominic Watson

Or, indeed, a somewhat tidier version:

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

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!