When Should You Use Outerhtml In Javascript?
Solution 1:
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.
<divid="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 = '<divid="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><ulid="exampleB"><li>House Blend</li></ul><script>
document.getElementById("exampleB").innerHTML = '<li>Sumatra blend</li><li>Kenyan</li><li>Colombian medium blend</li>';
</script>
Solution 2:
functiongetHTML(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;
}
Solution 3:
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.
Post a Comment for "When Should You Use Outerhtml In Javascript?"