0

I have a element that append to body when user click on a button. I want to remove appended element by clicking on it. How can I do this?

Code

    $("#btn1").click(function() {
      $("body").append("<div class='someClass'></div>");
  });
  $(".someClass").click(function() {
      $(this).remove();
  });
.someClass{
  width:100px;
  height:100px;
  background:green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">append div</button>
Bharti Mohane
  • 661
  • 7
  • 19
Majid
  • 95
  • 2
  • 9
  • You need to use a [delegated event handler](http://api.jquery.com/on/#direct-and-delegated-events) – Pete Jun 18 '18 at 10:22

2 Answers2

4

You need to use $(document).on('click','.someClass', function(){...} syntax. This is because when the JQuery is loaded the element with class someClass do not exist in DOM. And you want to associate a click event into it. Thus, you need to listen for click of that element from document level so that when .someClass element is added in DOM it recognise the click event for it.

$("#btn1").click(function(){
  $("body").append("<div class='someClass'></div>"); 
});
$(document).on('click','.someClass', function(){
  $(this).remove(); 
});
.someClass{
  width:100px;
  height:100px;
  background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1">append div</button>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

The problem is that the click event will only apply to elements that already exist. Because you are adding elements dynamically you will need to use the on() method instead. This will add the event to both existing elements and elements that are dynamically added later on.

For example:

$(document).on('click', '.someClass', function(){
    $("body").append("<div class='someClass'></div>");  
});
musefan
  • 47,875
  • 21
  • 135
  • 185