Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use outerHTML in JavaScript? [closed]

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?

like image 826
symfony Avatar asked Mar 20 '10 14:03

symfony


People also ask

What does outerHTML do in Javascript?

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.

Why you shouldn't use innerHTML?

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 .

What does outerHTML return?

The outerHTML property sets or returns the HTML element, including attributes, start tag, and end tag.

What is the difference between innerHTML and outerHTML in Javascript?

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.


2 Answers

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>
like image 111
tvanfosson Avatar answered Nov 07 '22 12:11

tvanfosson


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;
}
like image 38
kennebec Avatar answered Nov 07 '22 11:11

kennebec