How to insert HTML code with JavaScript

Sometimes we may want to add some HTML code into a specific DIV with JavaScript.

We can do this easily with innerHTML.

document.getElementById('yourDivId').innerHTML = '<b>Some HTML</b>';

Example:

Add a list element to HTML DIV with JavaScript.

<div id="exampleDiv"></div>

<script>
    document.getElementById('exampleDiv').innerHTML = '<ul><li>List element</li></ul>';
</script>

Output:

  • List element

If you want to leave the current HTML content without overwriting it, use innerHTML with += instead of =.

Example:

Add some HTML code to existing DIV content with JavaScript.

<div id="helloElement">Hello!</div>

<script>
    document.getElementById('helloElement').innerHTML += ' <b>How are you?</b>';
</script>

Output:

Hello! How are you?