原生JS 更换节点标签参考

参考CKeditor中的element方法

renameNode详细代码

/**
 * Changes the tag name of the current element.
 *
 * @param {String} newTag The new tag for the element.
 */
renameNode: function( newTag ) {
    // If it's already correct exit here.
    if ( this.getName() == newTag )
        return;

    var doc = this.getDocument();

    // Create the new node.
    var newNode = new CKEDITOR.dom.element( newTag, doc );

    // Copy all attributes.
    this.copyAttributes( newNode );

    // Move children to the new node.
    this.moveChildren( newNode );

    // Replace the node.
    this.getParent( true ) && this.$.parentNode.replaceChild( newNode.$, this.$ );
    newNode.$[ 'data-cke-expando' ] = this.$[ 'data-cke-expando' ];
    this.$ = newNode.$;
    // Bust getName's cache. (#8663)
    delete this.getName;
}

原生JS模拟(没有考虑IE8适配,属性复制可能不完全)

Element.prototype.renameNode = function(newTag){
      
      if(this.tagName == newTag)
        return;
      
      //var doc = this.ownerDocument;
      //create a new node
      var newElement = document.createElement(newTag);

      //copy all attributes
      if(newElement){
        for(var i=0;i

你可能感兴趣的:(原生JS 更换节点标签参考)