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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With