0

I have the following code: Html:

    <body>
      <div>
        <p  class='Go'>
          Create
        </p>
        <p class='Del'>
        Remove
        </p>
      </div>
   </body>

CSS:

.Go{
    background-color: lime;
    width:45px;
    text-align: center;
}
.bad{
    background-color:Red;
    width: 45px;
    text-align:center;
}
.Del{
    background-color:pink;
    width: 55px;
}

Javascript(Jquery)

$(document).ready(function(){
    $('.Go').click(function(){
       $('div').append("<p class='bad'>Delete</p>");
    });
    $('.bad').click(function(){
       $(this).remove();
    });
    $('.Del').click(function(){
       $('.bad').remove();
    })
});

The idea was that every time I clicked the "create", it would add a new "delete".

Every time I clicked the "remove", all the "delete"'s would go away, and every time I clicked a "delete", that single delete would be removed.

All but the last one works. Any ideas what mistake am I making here?

i.n.n.m
  • 2,936
  • 7
  • 27
  • 51
Lucian cahil
  • 83
  • 1
  • 2
  • 8
  • it's because the `Delete` elements are added after the page is loaded but the `.click` is bound to nothing since there are no `bad` divs when the page is loaded. – tima Aug 22 '17 at 02:02
  • what if you set the part you want to remove in a div. so if you click the remove all inside the div will be deleted. – Barclick Flores Velasquez Aug 22 '17 at 02:12

1 Answers1

2

In this situation you can't bind the jQuery click to an element that doesn't exist yet. You only bind the click on $(document).ready(). The way around this is to bind the delete you want to an element that exists when during the document ready function.

$('body').on('click', '.bad', function(){
  $(this).remove()
})

This says, whenever the body is clicked, if that event target has a class of .bad, then delete it. This way, the jQuery event is bound correctly.

Working example here: https://jsfiddle.net/xexhdfzw/1/

Beaut
  • 114
  • 2
  • 10