You cannot change the tag name of an existing DOM element; instead, you need to create a replacement, and then paste it where the element was.
The basis of this is to move the child nodes into substitution and similar copying of attributes. For example:
var wns = document.getElementById("93");
var lmn = document.createElement("lmn");
var index;
while (wns.firstChild) {
lmn.appendChild(wns.firstChild);
}
for (index = wns.attributes.length - 1; index >= 0; --index) {
lmn.attributes.setNamedItem(wns.attributes[index].cloneNode());
}
wns.parentNode.replaceChild(lmn, wns);
: ( div p, wns lmn, , )
document.getElementById("theSpan").addEventListener("click", function() {
alert("Span clicked");
}, false);
document.getElementById("theButton").addEventListener("click", function() {
var wns = document.getElementById("target");
var lmn = document.createElement("p");
var index;
while (wns.firstChild) {
lmn.appendChild(wns.firstChild);
}
for (index = wns.attributes.length - 1; index >= 0; --index) {
lmn.attributes.setNamedItem(wns.attributes[index].cloneNode());
}
wns.parentNode.replaceChild(lmn, wns);
}, false);
div {
border: 1px solid green;
}
p {
border: 1px solid blue;
}
<div id="target" foo="bar" onclick="alert('hi there')">
Content before
<span id="theSpan">span in the middle</span>
Content after
</div>
<input type="button" id="theButton" value="Click Me">
Hide result. .
. id, . HTML ( HTML5), CSS , jQuery, CSS .