What is outerHTML in JavaScript?

The outerHTML property is used to set and get the HTML content of the element and its children.

Syntax

Get HTML Content

let htmlString = element.outerHTML;

Set HTML content

element.outerHTML = htmlString;

When we set the outerHTML of an element, the element and all the child nodes of the element are replaced with the passed HTML StringThe passed HTML String is parsed internally..

Example

Console

In the code above, we have created a div and added some content to it.

  • We access the outerHTML property of the div element to get the HTML of the div and its children.

  • When we set the outerHTML of an element, the element and its children are replaced with the passed HTML String.


Points to be noted

If we set outerHTML to an element that has no parent elemente.g., elements that are not appended to the DOM, DOMException will be thrown.


var p = document.createElement("p");
p.outerHTML = "<p> not replaced </p>";
console.log(p.outerHTML); // DOMException


When we get the HTML content through the outerHTML property, if the HTML String contains &, <, > characters, then it will be replaced by the &amp; , &lt;, &gt; entities, respectively.

var a = document.createElement("a");
a.href = "https://test.com?id=10&name=t";
console.log(a.outerHTML); 
// <a href="https://test.com?id=10&amp;name=t"></a>

Imagine that we have a variable reference for an element. We replace the HTML content of the element using outerHTML property. In this case, the variable still points to the replaced element.

var divEle = document.getElementById("content");
console.log(divEle);
divEle.outerHTML = "<div>This div replaced a paragraph.</div>";
console.log(divEle); // even the div element is replaced. The divEle variable   still have reference to the replaced element.