Search code examples
javascripthtmlduplicatesinnerhtml

How to delete the last div with JavaScript


This function duplicates my div.

How can I delete the last div?

function duplicate_it(myid,myform) { 
 var x = document.getElementById(myid).innerHTML;
 document.getElementById(myform).innerHTML += x; 
}

Solution

  • It is not duplicating it. It is grabbing the innerHTML and addeding it to myForm.

    If you want to delete something, add a counter and wrap it in a container:

    cnt=0;
    function duplicate_it(myid,myform) { 
      var x = document.getElementById(myid).innerHTML;
      document.getElementById(myform).innerHTML += '<div id="xx'+(cnt++)+'">'+x+'</div>';
    }
    

    now you can delete document.getElementById("xx"+(cnt-1))

    A cleaner way is

    cnt=0;
    function duplicate_it(myid,myform) { 
      var div = document.createElement("div");
      div.id="xx"+(cnt++);
      div.innerHTML = document.getElementById(myid).innerHTML;
      document.getElementById(myform).appendChild(div);
    }