-1
function adddiv {
   var c1 = document.getElementById('area1').value;
   var divElement = document.createElement("div");  
   divElement.id = "myDiv";  
   divElement.className = "myDivClass";  
   divElement.innerHTML = c1;  
   document.body.appendChild(divElement);
}

above is my code to add div dynamically with button.

how would I remove the divs dynamically with button?

dfeuer
  • 48,079
  • 5
  • 63
  • 167
user3303871
  • 25
  • 1
  • 8
  • 2
    possible duplicate of [Remove an element from the DOM from reference to element only](http://stackoverflow.com/questions/7561277/remove-an-element-from-the-dom-from-reference-to-element-only) – Sheepy Feb 08 '15 at 16:48
  • You can assign a unique id or class name and select & remove it when needed. Otherwise keep a reference to it by assigning it to a variable. – Sam Feb 08 '15 at 16:50

3 Answers3

3

your function declaration is wrong.Yor missed closing brackets in function declaration.it will be

function adddiv(){}

use removeChild () method.

document.body.removeChild(divElement);

As functions in javascript creates own scope,The divElement is inside the private scope of adddiv function.If you want to delete you need the removeChild method defined inside adddiv function;

if you want it accessible from any where in your script,define divElement as global variable or create this variable directly on window object from within adddiv function.

window.divElement = document.createElement("div");  

function adddiv() {
  
   var divElement = document.createElement("div");  // private scope
   divElement.id = "myDiv";  
   divElement.style='width:100px;height:100px;border:1px solid black;'
   divElement.className = "myDivClass";  
   divElement.innerHTML = 'new div';  
   document.body.appendChild(divElement);
    var btn=document.getElementById('btn');
   btn.addEventListener('click',function(){  // if this function is defined outside it won't work because divElement will be out of its scope
         document.body.removeChild(divElement);
   });
   
}
  

window.addEventListener('load',adddiv);
<input type='button' value='remove' id='btn'>
AL-zami
  • 8,902
  • 15
  • 71
  • 130
0

You can just store that div in a variable and remove it later:

function adddiv {
   var c1 = document.getElementById('area1').value;
   var divElement = document.createElement("div");  
   divElement.id = "myDiv";  
   divElement.className = "myDivClass";  
   divElement.innerHTML = c1;  
   document.body.appendChild(divElement);

   // get button element
   var button = document.getElementById("..");
   button.addEventListener("click", function() {
       divElement.parentNode.removeChild(divElement);
   });
}
kelunik
  • 6,750
  • 2
  • 41
  • 70
0

Or you can use the id:

var div = document.getElementById('myDiv'); 
div.remove();
Sebsemillia
  • 9,366
  • 2
  • 55
  • 70
Alexandre
  • 16
  • 3