Thursday, October 20, 2011

jQuery Rename Attribute (renameAttr)

I woke up this morning with a very unusual urge to make a rename attribute function for jQuery. I know, right.. that's just too weird! So after messing around with it, I decided that it needed to update the data as well. Here is the code I ended up with:

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

1 comment:

  1. I modified it to rename onclick attributes and rebind them.


    jQuery.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-','') ); }
    }
    });
    }
    });

    ReplyDelete

Note: Only a member of this blog may post a comment.