Search code examples
javascripteventsdomgarbage-collectionnode-webkit

Will JS remove dunamically created element with event listener if it's not connected to the DOM?


Let's imagine that we have a code like this:

function someName(callback) {
  var elem = document.createElement('input');
  elem.addEventListener('change', function(evt) {
    callback();
  }, false);
  // some code
  elem.click();
}

// some code

someName(function() {
  alert("Hello world!");
});

The question is: will JS completely remove the "elem" element created in the "someName" function after moving out of it's callback's context? The other question is: will JS remove the "elem" element if it is not changed after emitting the "click" event?

Can you, please, explain me when the "elem" element will be removed?

P.S.: I'm trying to write a simple application with node-webkit and such kind of code is needed to let node-webkit open a file dialog (open file, save file and so on) and handle it's result.


Solution

  • Variables defined inside a function only exist inside the function when the function is executed.

    Your code creates an input element and it assigns a callback function to it's state change handler, but you don't actually attach/insert the element to the DOM anywhere, so the element only exists as that variable; it never becomes something in the DOM to exist after the function ends

    Therefore when the function ends, the variable will be destroyed and that element wouldn't exist anymore, including the state change handler.

    sidenote: it's .createElement() not .create() (unless you have code that defined a .create() method..)