Remove from the DOM by itself does not remove the event headphones. An example of this is that we can keep a reference to the element:
const inicio = new Date();
const test = document.getElementById('test');
test.addEventListener('click', function(segs) {
const agora = new Date();
console.log('clique! passados', Math.round((agora - inicio) / 1000), 'segundos');
});
test.remove();
console.log(test.parentElement);
test.click();
setTimeout(() => test.click(), 10000);
#test {
width: 100px;
height: 50px;
background: #0000FF;
}
#test.active {
background: #00FF00;
}
<span id="count">0</span>
<div id="test">
</div>
When a few years SPA (single page aplication) began to be popular and moving around a lot in the DOM without refresh of the page problems of memory leaks arose. Some of these leaks were because removing an element from the DOM does not release everything that was associated with the element.
You must also remove the event headphones by passing the same function to the removeEventListener
method.
In your example this would be:
const test = document.getElementById('test');
const adicionarClasse = function() {
this.className = 'active';
}
const removerClasse = function() {
this.className = '';
}
test.addEventListener('mouseover', adicionarClasse);
test.addEventListener('mouseout', removerClasse);
setTimeout(function() {
test.removeEventListener('mouseover', adicionarClasse);
test.removeEventListener('mouseout', removerClasse);
test.remove();
}, 5000);
#test {
width: 100px;
height: 50px;
background: #0000FF;
}
#test.active {
background: #00FF00;
}
<div id="test">
</div>
Related: an MDN article on memory leaks ( in English )