Saturday, October 22, 2011

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 download. Please read "README" before using it.

Required: Javascript, HTML.

Using:
    1. <script type="text/javascript">
    2.       var i = 0;
    3.       function creatediv()    
    4.      {
    5.             i++;
    6.             var newelement = document.createElement('div');
    7.             newelement.setAttribute('id', i);
    8.             newelement.innerHTML = 'This is newly created div.';
    9.             var parentelement = document.getElementById('presentdiv')
    10.             parentelement.appendChild(newelement);
    11.             //var firstchild = parentelement.firstChild;
    12.             //parentelement.insertBefore(newelement, firstchild);
    13.              
    14.      }
    15. </script>
    16. <html>
    17. <body>
    18.              <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>
    19. </body>
    20. </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: 
    Uncomment the line 11 and 12 if you want to insert 'newelement' before 'firstchild'.
    Also see lastChild and returning values of firstChild and lastChild.

No comments:

Post a Comment

Thank you for your comment!