Sometimes, we want to replace a DOM element in place with JavaScript.
In this article, we’ll look at how to replace a DOM element in place with JavaScript.
Use the parentNode.replaceChild Method
We can replace a DOM element in place with JavaScript by getting the parent of the element we want to replace.
Then we can call the replaceChild
method on it to replace the element in place of the current child element of the parent.
For instance, if we have the following HTML:
<div>
hello world
</div>
Then we can do the replacement by writing:
const div = document.querySelector("div");
const span = document.createElement("span");
span.innerHTML = "hello james";
div.parentNode.replaceChild(span, div);
We get the div with document.querySelector
.
Then we create a span that we want to replace the div with with document.createElement
.
Next, we set the content of the span by setting the innerHTML
property.
And finally, we call div.parentNode.replaceChild
with the span
and the div
to replace the div with the span.
Now we should see ‘hello james’ in place of ‘hello world’
Use the replaceWith Method
An easier way to replace an element with another is to use the replaceWith
method.
To use it, we write:
const div = document.querySelector("div");
const span = document.createElement("span");
span.innerHTML = "hello james";
div.replaceWith(span);
In the last line, we call div.replaceWith
with span
to replace the div
with the span
.
And we get the same result as the previous example.
Conclusion
We can replace a DOM element in place by getting the parent node of the element we want to replace and call replaceChild
on the parent node.
Or we can call the replaceWith
on the element we want to replace and pass in the element we want to replace as the argument.