How to use innerHTML In Javascript

In this approach we are using the innerHTML property to add a new element to the HTML DOM . It involves setting the innerHTML of an existing element to include the HTML markup for the new element.

Syntax:

selctedHTMLElement.innerHTML = "newElement";

Example: The below example uses the innerHTML property to add a new element to HTML DOM.

JavaScript
<!DOCTYPE html>
<html>

<head>
    <title>Add Input Element to DOM</title>
</head>
<style>
    h1 {
        color: green;
    }

    #container {
        text-align: center;

    }

    button {
        cursor: pointer;
    }
</style>

<body>

    <div id="container">
        <h1>w3wiki</h1>
        <h4>Using innerHTML</h4>
        <button onclick="addInputElement()">
            Add Input Element</button>

    </div>


    <script>
        function addInputElement() {
            const container = document
                .getElementById('container');

            container
                .innerHTML += '<input type="text"
            placeholder = "Enter text..." > ';
        }
    </script>
</body>

</html>

Output:



How to Add a new Element to HTML DOM in JavaScript ?

Adding a new element to the HTML DOM dynamically using JavaScript is a common requirement in web development. This allows developers to create interactive and dynamic web pages without the need to reload the entire page.

There are several approaches to adding a new element to HTML DOM in JavaScript which are as follows:

Table of Content

  • Using createElement
  • Using innerHTML

Similar Reads

Using createElement

In this approach, we are using the createElement() method which is used to dynamically create a new HTML element. This method allows developers to create new elements and then insert them into the DOM....

Using innerHTML

In this approach we are using the innerHTML property to add a new element to the HTML DOM . It involves setting the innerHTML of an existing element to include the HTML markup for the new element....