The outerHTML
property is used to set and get the HTML content of the element and its children.
let htmlString = element.outerHTML;
element.outerHTML = htmlString;
When we set the outerHTML
of an element, the element and all the child nodes of the element are
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.
If we set outerHTML
to an element that has no 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 &
, <
, >
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&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.