0

The following code creates and removes a button with an onclick listener.

Does the onclick listener persist after the element is removed from the DOM?

let el = document.createElement('button')
el.innerHTML = "Test Button"
el.onclick = function(){
    alert('A Click Happened')
}

document.body.appendChild(el)
document.body.removeChild(el)

Bonus: Is the same true for el.addEventListener('click',() => { alert('clicked') })?

David Alsh
  • 6,747
  • 6
  • 34
  • 60
  • Logically: How can the listeners attached to the element persist after the element is destroyed? – met4000 Nov 10 '17 at 22:07

1 Answers1

1

No, it does not persist because you are removing the element with the onClick() attribute. The same is not true for addEventListener().

I feel like I am answering a test question for you, but I hope it helps. :)

Mirakolous
  • 164
  • 2
  • Whether handlers persist or not has nothing to do whether DOM elements are in DOM. It's about whether there is a reference to the element somewhere in code. – Wazner Nov 10 '17 at 22:13
  • He is defining the function inside the element. Therefore removing the element removes the function. There is no reason for it to persist since it only targets the referencing element. – Mirakolous Nov 10 '17 at 22:19
  • Removing an element is not the same as garbage collecting an element. – Wazner Nov 10 '17 at 22:30