JavaScript – innerHTML Property

The innerHTML property sets or returns the HTML content (inner HTML) of an element. It can be used to write the dynamic html on the html document.

Syntax

Return the innerHTML property:

HTMLElementObject.innerHTML

Set the innerHTML property:

HTMLElementObject.innerHTML = text

Property Values

ValueDescription
textSpecifies the HTML content of an element.
JavaScript – innerHTML Property Values

Return Value

This property returns a string that represents the HTML content of an element.

Example

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript - innerHTML Property Example</title>
</head>

<body>
    <h1>
        The New Tutorial
    </h1>
    <h2>
        DOM innerHTML Property
    </h2>
    <p id="p">EyWiah.com</p>

    <button onclick="test()">Click me!</button>
    <script>
        function test() {
            document.getElementById("p").innerHTML =
                "A computer science portal for geeks.";
        }
    </script>
</body>

</html>

Above example shows how to change the content of the paragraph tag using the innerHTML property.

Below example shows how to get the value of the paragraph tag using the innerHTML property.

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript - innerHTML Property Example - 2</title>
</head>

<body>
    <h1>
        The New Tutorial
    </h1>
    <h2>
        DOM innerHTML Property
    </h2>
    <p id="para">A computer science portal for geeks.</p>
    <p id="para-2"></p>

    <button onclick="test()">Click me!</button>
    <script>
        function test() {
            var x = document.getElementById("para").innerHTML;
            document.getElementById("para-2").innerHTML = x;
            document.getElementById("para-2").style.color = "green";
        }
    </script>
</body>

</html>