Element.prototype.setTagName=function(strTN) {
var oHTML=this.outerHTML, tempTag=document.createElement(strTN); //document.createElement will fire an error if string has wrong characters.
var tName={original: this.tagName.toUpperCase(), change: strTN.toUpperCase()}
if (tName.original == tName.change) return;
oHTML=oHTML.replace(RegExp("(^\<" + tName.original + ")|(" + tName.original + "\>$)","gi"), function(x){return (x.toUpperCase().replace(tName.original, tName.change));});
tempTag.innerHTML=oHTML;
this.parentElement.replaceChild(tempTag.firstChild,this);
}
使用(如果您想为正文的第一个元素设置跨度):
document.body.firstElementChild.setTagName("SPAN");
编辑:
我忘了提一件事。它创建了一个新元素,因此如果您将原始元素存储在变量中,则该变量将存储旧的(未更改的)元素。如果元素没有父元素,它会失败。
这就是为什么我做了一个新的:
Element.prototype.spawn = function(strTN = "spawn") {
let tName = ({original: this.tagName.toUpperCase(), change: strTN.toUpperCase()}); if (tName.original == tName.change) { return; }
let fragment = document.createRange().createContextualFragment(this.outerHTML.replace(new RegExp("(^\<\\b" + tName.original + "\\b)|(\\b" + tName.original + "\\b\>$)","gi"), function(x){return(x.toUpperCase().replace(tName.original, tName.change));}));
return(fragment.firstChild);
}
这个只是创建了包含所有原始后代的新元素,但如果需要,您必须手动将其放置到 DOM 中:
var e = document.body.firstElementChild;
e.replaceWith(e.spawn("i"));