Creating HTML elements dynamically

There are times when we want to create HTML elements on the page, result of a certain action. Below is explained how to do that using Javascript.

I have written a javascript which you can downloadPlease read “README” before using it.

Required: Javascript, HTML.

Using:

The javascript code for this is:
<script type="text/javascript">
var i = 0;
function creatediv()
{
 i++;
 var newelement = document.createElement('div');
 newelement.setAttribute('id', i);
 newelement.innerHTML = 'This is newly created div.';
 var parentelement = document.getElementById('presentdiv')
 parentelement.appendChild(newelement);
 var firstchild = parentelement.firstChild;
 parentelement.insertBefore(newelement, firstchild);
}
</script>

HTML code for this is:

<html>
<body>
<div id="presentdiv">This div is present here from the moment the page is opened.<input type="button" value="Click to create new div" onclick="javascript:creatediv();"></div>
</body>
</html>
Explanation:

First, we see the div ‘presentdiv’. It has two nodes, first is the text node and another is input ‘button’. New div is created on clicking button. How?

Look at the javascript function creatediv().

          6: A new div is created using createElement(). It takes the HTML tagname of element to be created as argument.

          7: setAttribtue() sets the attribute of the element using it. Like we have set ‘id’ as i, which is incrementing on every click.

          8: innerHTML is used if you want to add text to the element. Mostly used with div.

          9: We saved parentelement i.e., ‘presentdiv’ for further use instead of calling again and again.

          10: appendChild() is called to append  the element we just created, div(i). It appends at the end of the ‘parentelement’.

          11: This line is used if we want to add new element at the beginning of parent element. ‘firstChild’ returns the first child of the ‘parentelement’.

          12:  insertBefore() is used if new element is to be inserted before the some element we know. Here we insert ‘newelement’ before ‘firstchild’.

Note:

    Also see lastChild and returning values of firstChild and lastChild.

Leave a Reply

Your email address will not be published. Required fields are marked *