It is straightforward to replace the DOM element in javascript with some other element.
replaceWith() method is used to replace the HTML element in Javascript.
Follow is the working example:
This is a span element
Code:
<html>
<head>
<script>
function replaceElement(){
// Create an element first
var h1Element = document.createElement("h1");
h1Element.innerHTML = "This is h1 element"
var el = document.getElementById("span");
// Replace the span with h1
el.replaceWith(h1Element);
}
</script>
</head>
<body>
<span id="span"> This is a span element </span>
<input type="submit" onclick="replaceElement()" value="Click me to change above span to h1" />
</body>
</html>
Explanation
In the above example, when the button is clicked, we are creating a new element i.e. h1, and replacing the span element with the h1 element.