The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.
To only obtain the HTML representation of the contents of an element, or to replace the contents of an element, use the innerHTML property instead.
Reading the value of outerHTML returns a string containing an HTML serialization of the element and its descendants. Setting the value of outerHTML replaces the element and all of its descendants with a new DOM tree constructed by parsing the specified htmlString.
HTML
<div id="d">
<p>Content</p>
<p>Further Elaborated</p>
</div>
JavaScript
const d = document.getElementById("d");
console.log(d.outerHTML);
HTML
<div id="container">
<div id="d">This is a div.</div>
</div>
JavaScript
const container = document.getElementById("container");
const d = document.getElementById("d");
console.log(container.firstElementChild.nodeName);
d.outerHTML = "<p>This paragraph replaced the original div.</p>";
console.log(container.firstElementChild.nodeName);
If the element has no parent node, setting its outerHTML property will not change it or its descendants. For example:
const div = document.createElement("div");
div.outerHTML = '<div class="test">test</div>';
console.log(div.outerHTML);
Also, while the element will be replaced in the document, the variable whose outerHTML property was set will still hold a reference to the original element:
const p = document.querySelector("p");
console.log(p.nodeName);
p.outerHTML = "<div>This div replaced a paragraph.</div>";
console.log(p.nodeName);
The returned value will contain HTML escaped attributes:
const anc = document.createElement("a");
anc.href = "https://developer.mozilla.org?a=b&c=d";
console.log(anc.outerHTML);