原生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<this.attributes.length;i++){
            newElement.setAttribute(this.attributes[i].name,this.attributes[i].nodeValue);
        }
      }

      //move children to the new node
      while(this.firstChild){
        newElement.appendChild(this.firstChild);
      }

      //replace the node
      var parentNode = this.parentNode;
      parentNode.replaceChild(newElement,this);
    };
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,823评论 25 709
  • debug 是程序媛必备技能之一,Get 到这个技能,会大大提高你的工作效率。再加上,放假前林老师特地教了我们最简...
    芝麻香油阅读 2,372评论 4 5
  • 乔帮主虽然已经远去,但是他带给时代的启示以及带来的手机革命深刻地影响着时代浪潮的人们。乔帮主的“求知若渴,大智若愚...
    职场小白果阅读 3,754评论 0 1