views:

82

answers:

4

When I delete a DOM element using .removeChild(), the reference to the element still returns it as a valid element:

var someNode = document.getElementById("someid");

if(someNode)
    alert('valid element');
else
    alert('invalid');

var p = document.getElementById('parent_id');
p.removeChild(someNode);


if(someNode)
    alert('valid element');
else
    alert('invalid');

Both before and after, I get a "valid" in the alert box. How do I delete the DOM element without this occuring? I tried jQuery's .remove() but it was no better.

+4  A: 

removeChild removes the dom element from the document (as does jquery's .remove()). Since you are keeping a reference to it in the variable someNode, it will not be garbage collected by the browser, and you will still be able to refer to the dom element using someNode. You can even reinsert it into the document somewhere else.

in order to completely remove all references to the dom element, you need to unset someNode with someNode = null; or try to re-retrieve the element from the dom

barkmadley
A: 

Just after removing the node update

someNode = document.getElementById("someid");

and check whether it returns valid or not. The object is instantiated at the first time and it will keep that until an update is made to that variable. Updated DOM will not be visible to the variable unless you refer that again.

rahul
A: 

Define 'valid'. If you mean 'part of the document' then something like:

function isElementInDocument(element) {
    while (element = element.parentNode) {
        if (element === document) {
            return true;
        }
    }
    return false;
}

… should do the trick.

David Dorward
A: 

By setting someNode to equal the element, you make its value an object, represetning the element. Essentially, you've saved all the information about the element to this variable. Therefore, to strip it from the variable, you need to use someNode = undefined.

A neat way to do this would be the following

if(p.removeChild(someNode){
    someNode = undefined;
}
Gausie