The 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:

<div id="app">
  <h1>Heading 1</h1>
  <p>Paragraph</p>
</div>

I might select the div using the querySelector() method:

var app = document.querySelector("#app");

To replace the element with an image, I could update its outerHTML property:

app.outerHTML = "<img src='chocolate-lab.jpg' alt='A chocolate Labrador'>";

Notes

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 NoModificationAllowedError.

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>"
console.log(div.outerHTML);

The new 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 div element.

Browser support

The outerHTML property is supported back to IE4. You can check out the browser compatibility in the MDN Web Docs.

Summary

You can use the outerHTML property to replace an HTML element with a completely new one.

Learn more:

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!