简体   繁体   中英

What happens to event listeners when element is removed?

If, for example, I have series of event listeners created like this:

var els = document.getElementyById('myList').getElementsByTagName('li');
for (i=0;i<els.length;i++) {
    els[i].addEventListener(eventType, function(e){ /* do stuff */ }, true);
}

First off, am I committing some kind of heresy like this? I mean, is there a faaar simpler way of doing this other than an event for each <li> element?

In either case, the main question is: what happens to those event listeners if the <li> s are removed/replaced? What would happen if I did this:

document.getElementyById('myList').innerHTML = 'Hello World!';

Do the listeners stay 'suspended' thus slowing down the browser (assume I have a lot of <li> s), or are they automatically removed? Is it even an issue?

Event handlers assigned to destroyed elements are marked for garbage collection. Meaning they are removed from memory. Also, if every one of your events does the same thing, bind them to the encompassing <ul> - click events will bubble up from the li s to the ul .

Also,

"is there a faaar simpler way of doing this other than an event for each <li> element?"

Using a delegated handler attached to the containing ul element makes sense here. Not necessarily simpler, but only slightly more complicated and more efficient - or maybe it is simpler if you are dynamically adding li elements. And it completely avoids the issue you are worried about.

(Courtesy of @nnnnnn)

Converted comment to answer as it seems to have helped answer the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM