I know that for Javascript events best practice is always remove events that you are no longer use. But what about the event that is attached to a HTML DOM element that I am going to remove, should I remove the event first then remove the DOM element or I can just remove DOM element straight away and not worry about the event that is attached to it?
Example:
const mainContainerEl = document.querySelector('.main-container');
const addBtnEl = document.querySelector('.add-btn');
const removeBtnEl = document.querySelector('.remove-btn');
const outputTextContent = (e) => {
console.log(e.currentTarget.textContent);
}
addBtnEl.addEventListener('click',()=>{
/* Click to create 5 span DOM elements and add event to each
one then append each one of them to mainContainerEl */
for(let i = 1; i <= 5; i++){
const newSpanEl = document.createElement('span');
newSpanEl.textContent = i;
newSpanEl.addEventListener('click', outputTextContent);
mainContainerEl.append(newSpanEl);
};
});
/* Should I do something like this? */
removeBtnEl.addEventListener('click',()=>{
if(mainContainerEl.firstChild){
const mainContainerElChildren = [...mainContainerEl.children];
mainContainerElChildren.forEach((childEl)=>{
/* Remove event first*/
childEl.removeEventListener('click',outputTextContent);
/* After the event is removed, remove the element */
childEl.remove();
});
}
});