Add or Append HTML code to a DIV element using JavaScript

← PrevNext →

You can use the innerHTML attribute in JavaScript to add or append an HTML code dynamically to a DIV element (or any element). Let’s see some examples.
<!DOCTYPE html>
<html>
<body>
    <div id='cont'>
        <p>
            Hello world :-) 
        </p>
    </div>
    
    <p>
        <input type='button' id='bt' 
            value='Click it' onclick='addHTML(cont)' />
    </p>
</body>

<script>
let addHTML = (ele) => {
    ele.innerHTML = '<p>Hello, I am Arun Banik</p>'; 
}
</script>
</html>
Try it

Click the Try it button to see how it works.

Well, I have a <div> element inside the <body> tag and a button. The <div> has a <p> element with a text Hello world :-). When you click the button, it adds a new HTML code to the DIV element, overwriting the old value or text.

The innerHTML attribute adds an HTML code. Look carefully, the string Hello, I am Arun Banik is inside the

tags. This makes it an HTML code. Its not a plain text.

Remember: innerHTML attribute is different from innerText attribute. If you want to add plain text to an element, then you must use the innerText attribute like this.

ele.innerText = 'Hello, this is a test.';

Events Listeners will be Lost

And also remember, the above code will replace the previous HTML code with a new HTML code. Any event listener attached to the previous code will also be lost. Everything will be new. See this example.

<!DOCTYPE html>
<html>
<body>
    <div id='cont'>
        // The P element has a listner attached to it. See the script.
        <p id='pEle'>
            Hello world :-) 
        </p>
    </div>
    
    <p>
        <input type='button' id='bt' 
            value='Click it' onclick='addHTML(cont)' />
    </p>
</body>

<script>
// Add a listener.
document.getElementById('pEle').addEventListener("click", say_hi);

function say_hi() {
    alert('hi');
}

let addHTML = (ele) => {
    ele.innerHTML += '<p>Hello, I am Arun Banik</p>'; 
}
</script>
</html>
Try it
The <p> element in the above example is clickable. Since, I have added an Event Listener to it. However, when I am adding a new HTML code to the <div>, the listener is lost. An entirely new code is added.

In-addition, If you want to keep the previous HTML code(s) and add some new HTML code(s) to the <div> element, you can concatenate the values, like this.

<script>
let addHTML = (ele) => {
    ele.innerHTML += '<p>Hello, I am Arun Banik</p>'; 
}
</script>

Thanks for reading.

← PreviousNext →