参考CKeditor中的element方法
/**
* 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);
};
网友评论