outerHTML property in vanilla JS
You probably know you can use the
innerHTML property to update an element’s HTML content. But did you know you can use the
outerHTML property to replace an element entirely?
Imagine the following HTML:
I might select the
div using the
To replace the element with an image, I could update its
A few things to note…
You cannot update the document root
If you try to set the
outerHTML property on the root element, you will get a
It doesn’t matter if you try to get the element via:
None of these will work.
You can still get the
outerHTML property. You just can’t set it.
The element must have a parent
The element whose
outerHTML property you update must have a parent. If not, it will remain unaffected and some browsers will throw an error.
Here’s an example from the MDN Web Docs:
div is never added to the DOM, so it doesn’t have a parent element. Trying to update its
outerHTML property doesn’t work.
The variable still references the original element
In my original example, I saved the
div element to the
app variable. Then I used its
outerHTML property to replace it with an image.
Although the document gets updated, the
app variable still refers to the original
outerHTML property is supported back to IE4. You can check out the browser compatibility in the MDN Web Docs.
You can use the
outerHTML property to replace an HTML element with a completely new one.
Element.outerHTML in the MDN Web Docs
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!