When Will A Local Unattached DOM Element Be Garbage Collected?

Viewed 373

Objects in Javascript get garbage collected when they lose scope and are no longer referenced. However, when is an element not referenced anymore? Take the following IIFE below:

var el = (function() {
  // Generate DOM element, but don't attach it to DOM
  var div = document.createElement('div');
  // Provide interior content
  div.innerHTML = '<span>A</span><span>B</span>';
  // Get reference to first child element in div
  var result = div.firstChild;
  // Blow away all div content
  div.innerHTML = '';
  // Return original first child element
  return result;
})();

My question is twofold:

  1. Does removing the content in the div.innerHTML = ''; assignment also remove the references to any child nodes inside of it, or is it done so later during pre-memory retrieval of the garbage collection process?
  2. If the div had been attached to the DOM instead of a local variable that went out of scope as the function exited, would it make any difference?
1 Answers
Related