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
Example
In the code above, we have created a div and added some content to it.
-
We access the
outerHTMLproperty of thedivelement to get the HTML of thedivand its children. -
When we set the
outerHTMLof 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 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.