ZetCode

Element.innerHtml tutorial

last modified August 24, 2023

Element.innerHtml tutorial shows how to read and write HTML content with Element.innerHtml property in JavaScript.

Element.innerHtml

Element.innerHtml reads or writes the HTML markup contained within the element.

To insert the HTML into the document rather than replace the contents of an element, we use the insertAdjacentHTML method.

Document.all example

The following example demonstrates the usage of the document's all property.

index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Element.innerHtml</title>

    <link rel="stylesheet" href="main.css">
</head>

<body>

    <div class="container">

        <input id="input" type="text">
        <div id="output"></div>

        <button id="writeBtn">Write</button>
        <button id="readBtn">Read</button>

        <script src="main.js"></script>

    </div>
</body>

</html>

In the document, we have an input element and two buttons. The buttons read and write HTML content of a div element.

main.css
.container {
    display: flex;
}

#output {
    width: 18em;
    height: 2em;
    border: 1px solid lightblue;
    overflow: hidden;
}

* {
    margin: 15px 5px;
}

This is some basic styling for our document.

main.js
const input = document.getElementById('input');
const output = document.getElementById('output');
const writeBtn = document.getElementById('writeBtn');
const readBtn = document.getElementById('readBtn');

writeBtn.addEventListener('click', () => {

    let val = input.value;
    output.innerHTML = val;

});

readBtn.addEventListener('click', () => {

    let content = output.innerHTML;
    console.log(content); 
});

We add click listeners to buttons.

let val = input.value;

We read the entered value from the input.

output.innerHTML = val;

We copy the entered value into the output element using innerHTML property.

readBtn.addEventListener('click', () => {

    let content = output.innerHTML;
    console.log(content); 
});

Here we read the HTML content from the output and write it into the console.

In this article we have worked with the element's innerHTML property.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.