How to append HTML code to a div using JavaScript ?

There are two ways to append HTML code to a div through JavaScript

  • Using the innerHTML attribute
  • Using the insertAdjacentHTML() method

Using the innerHTML attribute:
To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.

Syntax:

element.innerHTML += "additional HTML code"

or

element.innerHTML = element.innerHTML + "additional HTML code"

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>How to Append HTML Code to a Div using Javascript</title>
    <style>
        body {
            text-align: center;
              
            padding: 5%;
        }
        h1{
            color:green;
        }
    </style>
</head>
  
<body>
    <div id="add_to_me">
        <h1>GeeksforGeeks</h1>
        <p>This is the text which has already been typed into the div</p>
    </div>
  
    <button onclick="addCode()">Add Stuff</button>
    <script>
        function addCode() {
            document.getElementById("add_to_me").innerHTML += 
              "<h3>This is the text which has been inserted by JS</h3>";
        }
    </script>
</body>
  
</html>

chevron_right