The innerHTML and outerHTML DOM properties allow you to read and write content on a webpage. You can use them to fetch markup or make changes to it, and the two are similar in many ways. But there is a significant difference.

When working with the DOM, you'll use innerHTML and outerHTML quite differently. Find out how to use these two properties with practical examples.

What Is Inner HTML?

The innerHTML property is part of the DOM and you can access it via JavaScript. You can use it to get or set the contents of an element. This content excludes the element's own tag and only includes the markup that represents the element's children, in the form of a string.

Consider this code sample:

        <html>

<body>
    <p id="myP">I am a paragraph.</p>

    <script>
    document.getElementById("myP").innerHTML = "Hello World";
    </script>
</body>

</html>

In your browser, you'll see a standard paragraph with the replacement text, like so:

inner HTML changes paragraph contents

The innerHTML property selects and changes the contents of the <p> element in this example.

What Is Outer HTML?

The outerHTML property is like innerHTML in many ways. You can use it to get or set the contents of a selected element. However, it also sets the markup representing the element itself. This includes the opening tag, any properties, and—where relevant—the closing tag.

Revisit the previous example to see how outerHTML differs:

        <html>

<body>
    <p id="myP">I am a paragraph.</p>

    <script>
    document.getElementById("myP").outerHTML = "<h1>This H1 replaced a paragraph.</h1>"
    </script>
</body>

</html>

In your browser, you should see something like this:

outerHTML replaces HTML content and tag

In this example, the outerHTML property changes the p element into an h1 element.

Know the Difference and When to Use These Properties

The innerHTML and outerHTML DOM properties have many similarities, but one key difference. The innerHTML property captures the HTML contents of an element. In contrast, the outerHTML property captures the HTML that represents the element itself and its content.

You can use these properties to read and write HTML content via the DOM. The DOM will be a common, important concept throughout your JavaScript development process.