Jquery removes dynamically created draggable divs

Im dynamically creating divs with a button using this function

var counter = 1;
$("#button1").click(function(){
 $("<div/>", {
   "class": "test" + (counter++),
    text: "",
  }).resizable().draggable()
  .appendTo("body");
});

How do I add another button to remove these dynamically created divs?

+3
source share
2 answers
$("#button1").click(function(){
 $("<div/>", {
   "class": "dynamic test" + (counter++),
    text: "",
  }).append('<div id="button"' + (counter -1) + '">Close</div>').resizable().draggable()
  .appendTo("body");

  $("#button" + (counter -1)).click(function(){
      $(".test" + (counter-1)).remove();
   });
});

You can also add a close button to each div created to close this div.

+1
source

Of course, just give a common class to each dynamically added element, in this case .dynamic. Then, when another button is pressed, any instance of this class is simply deleted.

var counter = 1;

$("#button1").click(function(){
 $("<div/>", {
   "class": "dynamic test" + (counter++), // note we're adding a new generic class
    text: "",
  }).resizable().draggable()
  .appendTo("body");
});

$("#button2").click(function(){
 $(".dynamic").remove();
});
+3
source

All Articles