0

I'm creating an .item element using Javascript, then I want to remove it by clicking. Why does .click() not work?

$('.item').click(function() {
    $(this).remove();
});

Working solution (why does it work? and why don't we always use this instead of .click()?):

$(document).on('click','.item',function() {
    $(this).remove();
});
jane
  • 385
  • 1
  • 4
  • 14

3 Answers3

3

$('.item') returns all of the elements with a class of item at the time you call the jQuery constructor with that selector. You then attach an event handler to each and every one of them. It isn't designed to account for new elements.

The event delegation syntax binds the click handler to document and handles all click events. If the event's target was an element that matches your selector (.item), the event is accepted.

See this question as well: Why not take Javascript event delegation to the extreme?

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
2

The reason could be the .item elements are added dynamically

When you use $('.item').click(..) it binds the click handler only to those elements which exists in the dom at that moment of time, so if an elements is added after this statement is executed the click handler will not will attached to the new elements.

when you use $(document).on('click','.item',function() {}); to register click event handler, it makes use event propagation to work. In the dom event structure an event from an element will get bubbled up to the document object. id if a element is clicked the click handlers attached to it and its parent elements will get triggered unless the event propagation is prevented. So in this method the click eveht handler is registered to the document object, so when the click event from an element is bubbled upto the document object it tests the events source element(or its parent) with the passed filter in this case .item and it is true then the handler is executed

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Because the elements are created dynamically after the page load...

Another solution

$('body').delegate('.item','click',function() {
    $(this).remove();
});
coolguy
  • 7,866
  • 9
  • 45
  • 71