poashoas
poashoas

Reputation: 1894

jQuery: removing elements and what about the event listener?

Just curious, what happends to the event Listener

$('a.someclass', 'div.contextClass').on('click', function someFunction(){
    console.log('clicked!');
});

when I remove div.contextClass

$('div.contextClass').remove();

Do I first need to do this?

$('a.someclass', 'div.contextClass').off('click');

Upvotes: 0

Views: 28

Answers (2)

ProllyGeek
ProllyGeek

Reputation: 15856

Please refer to jquery reference documents here

.remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59292

No.

When the context or parent (<div>) itself is removed, everything within it (<a>) gets removed from the DOM. The event handler only executes the handler when the event takes place.

But when the element itself is not present, it gets no events which can then be handled because you don't have the element to do something like click or focus or something.

Upvotes: 3

Related Questions