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);
}
Use (in case you want to set a span for body's first element):
document.body.firstElementChild.setTagName("SPAN");
EDIT:
I forgot to mention something. It creates a new element so if you have the original one stored in a variable, the variable will be storing the old (unchanged) one. If the Element doesn't have a parent Element it fails.
That's why I made a new one:
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);
}
This one just creates the new Element with all the original descendants but you have to place it to the DOM manually if you want:
var e = document.body.firstElementChild;
e.replaceWith(e.spawn("i"));