Add/Remove Elements in HTML using Java Script


The code below is a simple example of Add, Remove elements in HTML file by updating DOM Tree.
<html>
    <head>
       <title> foo testing.. </title>
       <script>
       function addElement(num) {
           for( i=1; i <= num; i++) {
                  var element = document.getElementById('inputs');
                  var name = "input"+i;
                  var divId = "divid"+i;
                  var newdiv = document.createElement('div');
                  newdiv.setAttribute('id',divId);
                  newdiv .innerHTML = "Input"+i+": <input type='text' name='"+name+"'>";
                  newdiv .innerHTML +="&nbsp;<a href='#' onclick='removeElement(\""+divId+"\")'>Remove</a>";
                  element.appendChild(newdiv);
           }
       }
       function removeElement(divNum) {
               alert (divNum);
               var doc = document.getElementById('inputs');
               var olddiv = document.getElementById(divNum);
               doc.removeChild(olddiv);
           }
           </script>
   </head>
   <body>
        Enter the value: <input type='text' name='number' onblur='addElement(this.value)'>
        <div id = 'inputs'>
        <!-- Elements will be added here -->
        </div>
  </body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: