How can I change HTML attribute names with jQuery?

后端 未结 7 1382
無奈伤痛
無奈伤痛 2020-11-30 06:51

I would like to change all the names of the attributes where class=\"testingCase\" throughout all my whole html document.

e.g. Change:

&         


        
相关标签:
7条回答
  • 2020-11-30 07:24

    A little later but this link has a great jquery function extension:

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

    Example

    // $(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 );
    

    I DID NOT WRITE THIS. BUT I DID TEST IS WITH JQ 1.10. THE CODE IS FROM THE LINK.

    0 讨论(0)
提交回复
热议问题