How to append HTML code to a div using JavaScript?


To append HTML code to a div using JavaScript, we first need to select the div element. We can do this by using the document.getElementById() method and passing in the id of the div element. Next, we use the innerHTML property of the div element and set it equal to the HTML code we want to append, preceded by the += operator.

Approach

One approach to appending HTML code to a div using JavaScript would be to select the div using its id,

Then use the innerHTML property to add the desired HTML code. For example −

var div = document.getElementById('myDiv');
div.innerHTML += '<p>This is some new HTML code</p>';

Explained

In this example, we will append HTML code to a div using JavaScript.

  • First, we will create a div element −

<div id="container"></div>
  • Next, we will create a function that will append HTML code to the div element −

function appendHtml() {
   var div = document.getElementById('container');
   div.innerHTML += '<p>This is some HTML code</p>';
}
  • Finally, we will call the function when the page loads −

window.onload = function() {
   appendHtml();
}

Example

<!DOCTYPE html>
<html>
<head>
   <title>Append HTML Code</title>
</head>
   <body>
      <div id='container'></div>
      <script>    
         function appendHtml() {
            var div = document.getElementById('container');
            div.innerHTML += '<p style="color:black">This is some HTML code</p>';
         }       
         window.onload = appendHtml;
      </script>
   </body>
</html>

Updated on: 16-Feb-2023

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements