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
var app = document.querySelector("#app");
To replace the element with an image, I could update its
app.outerHTML = "<img src='chocolate-lab.jpg' alt='A chocolate Labrador'>";
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:
// Create a new div element
var div = document.createElement("div");
// Try to set its outerHTML property
div.outerHTML = "<div class='test'>test</div>";
// Output: "<div></div>"
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.