jQuery.fn.extend({ renameAttr: function( name, newName, removeData ) { var val; return this.each(function() { val = jQuery.attr( this, name ); jQuery.attr( this, newName, val ); jQuery.removeAttr( this, name ); // remove original data if (removeData !== false){ jQuery.removeData( this, name.replace('data-','') ); } }); } });
Use it as follows:
// $(selector).renameAttr(original-attr, new-attr, removeData); // removeData flag is true by default $('#test').renameAttr('data-test', 'data-new' ); // removeData flag set to false will not remove the // .data("test") value $('#test').renameAttr('data-test', 'data-new', false );
Basically, it adds a new attribute with the same value and removes the old one. It automatically removes the jQuery data for the original attribute unless you set the "removeData" flag to false. Check out this demo
I modified it to rename onclick attributes and rebind them.
ReplyDeletejQuery.fn.extend({
//original http://wowmotty.blogspot.com/2011/10/jquery-rename-attribute-renameattr.html
//modified by C Daubert 12/20/12
renameAttr: function( name, newName, removeData )
{
return this.each(function() {
var val = jQuery.attr( this, name );
//ignore if blank or null
if (val)
{
//if onclick, will need bound not added as an attribute
if (newName == 'onclick')
$(this).bind('click', function () {eval(val);} );
else
jQuery.attr( this, newName, val );
jQuery.removeAttr( this, name ); // remove original data
if (removeData !== false){
jQuery.removeData( this, name.replace('data-','') ); }
}
});
}
});