Languages
[Edit]
EN

JavaScript - what is the difference between innerHTML and outerHTML?

14 points
Created by:
AnnLen
1771

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 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 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?
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.