Sometimes, we want to change HTML element type with JavaScript.
In this article, we’ll look at how to change HTML element type with JavaScript.
How to change HTML element type with JavaScript?
To change HTML element type with JavaScript, we can use the replaceWith
method.
For instance, we write:
const parent = document.createElement("div");
const child = document.createElement("p");
parent.appendChild(child);
const span = document.createElement("span");
child.replaceWith(span);
to create a div and p element with createElement
.
Then we append child
as the child of the parent
with appendChild
.
Next, we create a span with createElement
.
And finally, we call child.replaceWith
with span
to replace the p element with the span element as the child of the div.
Conclusion
To change HTML element type with JavaScript, we can use the replaceWith
method.