Reputation: 15
How can i find a node that is not attached?
A sample code:
var newElem = document.createElement('div');
newElem.id = 'newDiv';
newElem = null;
How do may i find the div
i just created?
document.getElementById('newDiv')
does not work because the div
is not attached to the document.
Upvotes: 1
Views: 241
Reputation: 4989
No matter you use newElem = null;
or not, document.getElementById('newDiv')
will return null
because the dom <div id="newDiv"></div>
you created is not attached to the document
.
You can use:
var newElem = document.createElement('div');
newElem.id = 'newDiv';
var existsElem = document.getElementById("any-existing-element");
existsElem.appendChild(newElem); // attach your created element to document
Then document.getElementById("newDiv")
will get your new created element.
Note: after existsElem.appendChild(newElem);
executed, even if you execute newElem = null;
, document.getElementById("newDiv")
still gets the dom <div id="newDiv"></div>
.
Upvotes: 0
Reputation: 59232
document.getElementById('newDiv')
does not work because the div is not attached to the document.
Exactly. You've already stored the reference to the element you just created. So why not use it instead?
Setting it to null
and asking how to find it, is unidiomatic.
All DOM methods act on nodes that are in the DOM or part of the DOM. If it isn't and if you're intentionally setting your own reference to null
, whatsoever may be the reason, you cannot refer back to it as there are no more references of it anywhere and hence it's garbage collected.
Upvotes: 2
Reputation: 664356
After you've set the newElem
reference you had to your element to null
, the node is garbage-collected. It doesn't exist any more, and you cannot find it.
When you are not attaching a node to a DOM part, you cannot use any DOM methods to find it in that part.
Upvotes: 3