Languages
[Edit]
EN

JavaScript - difference between innerHTML and outerHTML

14 points
Created by:
a_horse
538

In this article, we would like to show you the difference between innerHTML and outerHTML in JavaScript.

1. Overview

Outer HTML term in JavaScript describes HTML source code that is inside some element (Inner HTML) bounded by element tag code with all attributes.

The difference between innerHTML and outerHTML html:

  • innerHTML = HTML inside of the selected element
  • outerHTML = HTML inside of the selected element + HTML of the selected element

Let's take a look at the below example.

HTML example

<div id="element">
  <p>Hello world</p>
</div>

innerHTML

<p>Hello world</p>

outerHTML

<div id="element">
  <p>Hello world</p>
</div>

Another way to look at this is with below description + image

  • innerHTML = Enclosed tag content
  • outerHTML = Opening tag + Enclosed tag content + Closing tag
HTML tag construction
HTML tag construction

Now we can test it by ourselves with the below 2 practical code examples.

2. Code example 1

// ONLINE-RUNNER:browser;

<html>
<body>
  <div id="element">
    <p>Hello world</p>
  </div>
  <script>

    var element = document.getElementById('element');

    console.log('innerHTML:');
    console.log(element.innerHTML);

    console.log('outerHTML:');
    console.log(element.outerHTML);

  </script>
</body>
</html>

3. Code example 2

// ONLINE-RUNNER:browser;

<html>
<body>
  <div id="element">
    <h3>Head 1</h3>
    <p>Some apostrophe text...</p>
    <h3>Head 2</h3>
    <p>Some apostrophe text...</p>
  </div>
  <script>

    var element = document.getElementById('element');

    console.log('innerHTML:');
    console.log(element.innerHTML);

    console.log('outerHTML:');
    console.log(element.outerHTML);

  </script>
</body>
</html>

Merged questions

  1. JavaScript - inner vs outer html
  2. JavaScript - innerHTML vs outerHTML
  3. JavaScript - how to use innerHTML and outerHTML?

Alternative titles

  1. JavaScript - what is the difference between innerHTML and outerHTML?
  2. JavaScript - innerHTML vs outerHTML
  3. JavaScript - innerHTML and outerHTML comparison
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join