0

lets say i have got this simple html code

<div id="0">
   <div id="0:0">
      <div id="0:0:0"></div>
   </div>
   <div id="0:1"></div>
</div>

now lets add some javascript

let div_ids=["0","0:0","0:0:0","0:1"];
for(let i=0;i<div_ids.length;i++){
   document.getElementById(div_ids[i]).addEventListener("click",()=>{console.log("hi");});
}

now we have an EventListener for every div
now lets execute this javascript code

document.querySelector("body").removeChild(document.getElementById("0"));

my question : will removing div#0 delete his and his children's EventListeners ?

prewky
  • 25
  • 5
  • 1
    It's funny how some languages have genders for everything, but yes normally the event listeners are removed with the element (with some caveats). https://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory – ippi Aug 20 '21 at 01:42
  • Technically it will not be removed, https://jsfiddle.net/ramseyfeng/3rnauod8/ – huan feng Aug 20 '21 at 01:58
  • @huanfeng this fiddle only demonstrates that the setInterval callback keeps firing, it does say anything about the DOM element and its event handler. – Kaiido Aug 20 '21 at 02:02
  • @Kaiido thanks for the comments, then i think the answer is already explained well in https://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory – huan feng Aug 20 '21 at 02:13
  • Sure it is. I didn't dispute that, but your claim of the inverse of what is said there. – Kaiido Aug 20 '21 at 02:36

0 Answers0