Can I change an HTML element’s type?

Use the ChildNode.replaceWith() method to create a new node and replace the old node with the new one. As exemplified in MDN docs:

var parent = document.createElement("div");
var child = document.createElement("p");
parent.appendChild(child);
var span = document.createElement("span");

child.replaceWith(span);

console.log(parent.outerHTML);
// "<div><span></span></div>"

More information is available in this answer.

Leave a Comment