When should you use outerHTML in JavaScript? [closed]
Asked Answered
S

3

21

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?

Sphygmoid answered 20/3, 2010 at 14:43 Comment(1)
You may want to check this: #2475105Alwyn
A
30

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>
Advocation answered 20/3, 2010 at 14:51 Comment(0)
V
12
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;
}
Venerable answered 20/3, 2010 at 15:7 Comment(2)
Interesting idea. However since most browsers that don't support outerHTML do support prototyping on HTMLElement I wonder if it would be easier to implement it pseudo-natively?Westland
This would benefit from an explanation as it is not clear how it answers the question in context. Perhaps the question was edited.Tactful
H
8

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.

Hubbard answered 20/3, 2010 at 14:53 Comment(2)
A year on, and Chrome and Safari also appear to have implemented this feature. However, at the time of writing this, Firefox does not support it.Dwarfish
Support for outerHTML was added in Firefox 11.Monotheism

© 2022 - 2024 — McMap. All rights reserved.