Suppose I create an element using $(‘some html‘), like this:
var imgSrc = determineImageURL();
var myImg = $('<img>', { src: imgSrc })[0]; // Creates a new <img>.
My question is:
- Who is the parent of the new element? document? window? none? Is this the same for all browsers?
- Suppose I need to run that code multiple times, and each time a possibly different imgSrc is computed. Do the new element become garbage (and may be collected) when myImg is changed or the current function returns? Or I must keep a single <img> and only change the src attribute?
The parent of
myImgdepends on where you append it to. Given only the code you quoted, it is none.The new element is garbage collected when the function returns, if you don’t attach the node to a parent in the function.
The variable declare with
varonly survive in function scope, unless you creates other reference to it (attached to a parent or referred in closure).