EN
JavaScript - difference between innerHTML and outerHTML
14
points
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
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>