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?
outerHTML property in javascript outerHTML property is used to get the specified HTML element including all its descendant content. This property can also be used to replace the contents in an element using the given one. In order to return only the descendant content, innerHTML can be used.
The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .
The outerHTML property sets or returns the HTML element, including attributes, start tag, and end tag.
The outerHTML is the HTML of an element including the element itself. Use the outerHTML when you want to completely replace an element and its contents. Use innerHTML when you only want to replace the contents of the element.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With