We help IT Professionals succeed at work.

Deleting a DOM Node

Medium Priority
680 Views
Last Modified: 2013-11-19
I have a script that replaces document.getElementById with a caching version of that.  Everything works fine except that when I delete a node then try to access it again I get a reference to the "Dead" node.

So my question is: how do I actually DELETE a DOM node?  "obj.parentNode.removeChild(obj)" simply removes it from the document and "delete obj" doesn't work.

Any ideas?



<div id="test">test</div>
<script>
var n = document.getElementById('test');
var x = n;

// Start Modifying any code.  do NOT change x itself

n.parentNode.removeChild(n);
delete n;

// End modifying any code

alert(x);      // I want this to be null or undefined
</script>
Comment
Watch Question

Jens FiedererTest Developer/Validator

Commented:
You can not get x to be null or undefined without changing the value of x.

Test Developer/Validator
Commented:
So
x = null;

or allowing x to go out of scope should work.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Jens FiedererTest Developer/Validator

Commented:
This is a side effect of Javascripts automatic memory management.

Once the node is removed from the document, and can no longer be reached from any variable, the garbage collector can reclaim the storage of the node.

As long as you keep a pointer to the node in x, javascript is NOT ALLOWED to really dispose of the node!
ZvonkoSystems architect
CERTIFIED EXPERT
Top Expert 2006

Commented:
Try:

    obj.removeNode(true);

But that works only in IE.


Jens FiedererTest Developer/Validator

Commented:
obj.removeNode(true);

cannot and should not have any influence on the contents of "x".
ZvonkoSystems architect
CERTIFIED EXPERT
Top Expert 2006

Commented:
Sorry, you are true.
I focused on DOM and the allover innerHTML content.
But that is the side effect of GarbagaCollection: as long as ONE reference to a storage object is alive, that long is that Object NOT discarded!
I was aware of that, but not to the final consequencies.

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.