Languages
[Edit]
EN

JavaScript - what is the difference between innerHTML and outerHTML?

14 points
Created by:
AnnLen
9180

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?
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join