Making div Appear with JavaScript

This tutorial shows how to make a div appear with JavaScript on the push of a button.

Again, we will be using the onClick event on a button, this time to demonstrate how you can insert a div element on the page when a button is pushed.

To achieve the desired effect, we will create a custom function that we can call when the button is clicked. This function will be using the innerHTML property to insert the div – in case you haven't worked with custom functions before, you may want to first read about them in the JavaScript Tutorial.

The Element Insertion Function

We will just be placing this script in the head section of a HTML page. The function that we will be calling with the onClick event looks like:

function insertDiv() {
  var parent = document.getElementById('ParentElementID');
  parent.innerHTML = '<div>This is a <em>div</em> element inserted by JavaScript.</div>';
}

The part which is hard for many to understand is the parent.innerHTML part – and the document.getElementById part for that matter. What it does, is basically: Take element referenced in variable parent and add this data to the element. where this would be the div that we want to add.

Making the HTML for the Script.

To make the script insert the div on the page, we will need a parent element with the ID of ParentElementID – which we also used as ID in the script earlier. Lets create a container div for this purpose. I.e

<body>
  <div id="ParentElementID"></div>
  <button onClick="insertDiv();">Insert DIV</button>
</body>

The button element from the above example, will activate the insertDiv function when clicked, which will insert our div into our parent element.

The Compiled Example

<!DOCTYPE html>
<html>

  <head>
    <title>Inserting a div with JavaScript</title>
    <script type="text/javascript">
      function insertDiv() {
        var parent = document.getElementById('ParentElementID');
        parent.innerHTML = '<div>This is a <em>div</em> element inserted by JavaScript.</div>';
      }
    </script>
  </head>

  <body>
    <div id="ParentElementID"></div>
    <button onClick="insertDiv();">Insert DIV</button>
  </body>

</html>

More JavaScript Tutorials

  1. Changing the Iframe src Value