What are the differences between when you should use innerHTML and outerHTML. And how would you best implement the outerHTML to replace or add content?
The outerHTML is the HTML of an element including the element itself. Contrast this with the innerHTML of the element, which is the HTML contained within an elements opening and closing tags. By definition, elements without both opening and closing tags do not have innerHTML.
Use the outerHTML when you want to completely replace an element and its contents.
You might do this if you have a loading section. The new content with the outerHTML replaces it.
<div id="exampleA" class="styleA">
<p>Here could be a default message where the div has specific styling. These are useful for things like default error or loading messages.</p>
</div>
<script>
document.getElementById("exampleA").outerHTML = '<div id="welcome" class="styleB">Welcome to the site</div>';
</script>
Use innerHTML when you only want to replace the contents inside the element.
An example of this would be if you have default content, but new data could at any point replace it.
<h2>Today's Coffees</h2>
<ul id="exampleB"><li>House Blend</li></ul>
<script>
document.getElementById("exampleB").innerHTML = '<li>Sumatra blend</li><li>Kenyan</li><li>Colombian medium blend</li>';
</script>
function getHTML(node){
if(!node || !node.tagName) return '';
if(node.outerHTML) return node.outerHTML;
// polyfill:
var wrapper = document.createElement('div');
wrapper.appendChild(node.cloneNode(true));
return wrapper.innerHTML;
}
outerHTML
was originally a non-standard Internet Explorer property of an element, but now has cross-browser support. It returns the HTML of the element and its child elements. For elements that have parents, it can be set to replace the element and its descendants.
© 2022 - 2024 — McMap. All rights reserved.