⬅︎ Back to Difference between $.data('foo') and $.attr('data-foo') in jQuery
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!
Or, indeed, a somewhat tidier version: $.fn.getData( function( attr ){ return this.attr( 'data-' + attr ) || this.data( attr ); } );
Comment
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
Or, indeed, a somewhat tidier version: $.fn.getData( function( attr ){ return this.attr( 'data-' + attr ) || this.data( attr ); } );