Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does removing an element also remove its event listeners? [duplicate]

An event associated with an item is removed if you also remove the element with removeChild()? Even if the item is removed with a simple this.innerHTML =''? The same applies to an event associated to an inline element like this <div onclick="/*this event*/"> </div>? Thanks in advance.

like image 493
user2809046 Avatar asked Dec 11 '22 11:12

user2809046


2 Answers

The answer is that it depends whether you have references to it or not.

var d = document.createElement('div');
otherElement.appendChild(d);
otherElement.removeChild(d);
// still have reference to d, it will exist, event listener remains even if it won't be fired.

If you no longer have a way to access it, the element will be garbage collected along with the listeners (for all browsers > IE6).

like image 167
Tibos Avatar answered Jan 26 '23 00:01

Tibos


I made the following test:

<div class="wrapper">
    <a href="#">Link</a>
</div>
<script type="text/javascript">
    window.onload = function() {
        var wrapper = document.querySelector(".wrapper");
        var link = document.querySelector("a");
        link.addEventListener("click", function() {
            console.log("click");
        });
        setTimeout(function() {
            wrapper.innerHTML = "";
        }, 4000)
    }
</script>

and monitor the results in the dev tools. After the loading of the page the events attached become from 5 to 6. The link is removed from the DOM and the events listeners become 5 again.

enter image description here

like image 21
Krasimir Avatar answered Jan 26 '23 01:01

Krasimir