美文网首页
原生JS 更换节点标签参考

原生JS 更换节点标签参考

作者: 冯瑞_FR | 来源:发表于2016-07-22 09:37 被阅读0次

    参考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);
        };
    

    相关文章

      网友评论

          本文标题:原生JS 更换节点标签参考

          本文链接:https://www.haomeiwen.com/subject/eigvjttx.html