outerHTML
The Complete Element
In the previous lesson, we learned that innerHTML grabs everything inside the selected element.
But what if you want to grab the content inside the element, AND the element itself? For that, you use the outerHTML property.
Reading outerHTML
Let's look at the difference when reading a node.
HTML:
<ul id="my-list">
<li>Item 1</li>
</ul>
JavaScript:
let list = document.getElementById("my-list");
console.log(list.innerHTML);
// Outputs: "<li>Item 1</li>"
console.log(list.outerHTML);
// Outputs: "<ul id="my-list"><li>Item 1</li></ul>"
As you can see, outerHTML includes the <ul id="my-list"> wrapper tag itself!
Replacing the Entire Element
When you assign a string to outerHTML, you aren't just replacing the content inside the element—you are completely destroying the selected element and replacing it with whatever you provide.
let list = document.getElementById("my-list");
// This destroys the <ul> entirely and replaces it with a <p>
list.outerHTML = "<p>The list has been removed!</p>";
Why use outerHTML?
It is less common than innerHTML, but it is very useful when you need to completely transform an element (e.g., turning a static <div> into an active <input> field when a user clicks an "Edit" button).
💡 Himanshu's Tip:
Once you replace an element using outerHTML, the original variable (e.g., let list) still holds a reference to the old, destroyed element in memory, but that element is no longer attached to the DOM. If you try to modify it again, nothing will happen on the screen!
Interview Questions
- What does
outerHTMLreturn compared toinnerHTML? - If you assign a new string to an element's
outerHTML, what happens to the original element? - What is the modern, preferred Vanilla JavaScript method for replacing an element instead of using
outerHTML? (Hint: look upreplaceWith()).