Search code examples
javascriptdomhtmlappendchild

adding dynamic content using javascript DOM


I want the following functionality in my webpage :-

when the add button is clicked, an entire div should get appended to a span. To achieve this I have attempted the below, but it does not seem to be working. Please explain why and how can i get this done.

<html>
<head>
  <script type="text/javascript">
     function add()
     {
        var details=document.getElementById('education');
        var eachDetail=document.getElementById('fdetails_edu_div');
        alert(details.getAttribute('id'));
        alert(eachDetail.getAttribute('id'));
        var x=details.appendChild(eachDetail);
        alert(x);
     }

  </script>
</head>
<body>
<span id="education">
<div id="fdetails_edu_div">
 <label>EDUCATIONAL QUALIFICATION
   <span class="small">Click on 'ADD' to add more qualifiaction details</span>
 </label>
 <button type="button" name="addqualifiaction" onclick="add()">ADD</button> 
 <br>
 <br>
 <br>
 <label>Degree
   <span class="small">School/Board</span>
 </label>
 <p>
   <input type="text" name="school_board" id="fdegree" size="30" maxlength="30" value="none"   class="fprjtit"/>
 </p>
 <br>
 <br>
 <br>
 <label>Year
   <span class="small">Year of Passing</span>
 </label>
 <p>
   <input type="text" name="pass_year" id="fdegree" size="30" maxlength="30" value="none" class="fprjtit"/>
 </p>
 <br>
 <br>
 <br>
 <label>Max Marks
   <span class="small">maximum marks</span>
 </label>
 <p>
   <input type="text" name="max_marks" id="fdegree" size="30" maxlength="30" value="none" class="fprjtit"/>
 </p>
</div>
</span>
</body>
</html>

now when i click on the add button the div with the id "fdetails_edu_div" should get appended as a child, preferably to the bottom, of the span with the id "education".

What is wrong with the below and how can it be corrected?


Solution

  • I think you need to clone the div with id fdetails_edu_div

    Use the following code

    var x = 1;
    
    function add() {
        var container = document.getElementById('education');
        var detail = document.getElementById('fdetails_edu_div');
        var clone = detail.cloneNode(true);
        clone.id = "fdetails_edu_div" + x;
        x++;
        container.appendChild(clone);
    
    }
    

    Notice, I create a new id for the newly created div.

    Also note, I have removed the Add button from within the div fdetails_edu_div and placed it outside (you don't want the add button to repeat, do you?)

    See working fiddle