Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if node exists in Javascript

Tags:

javascript

dom

Here's the deal - I've got a load of elements on a page, and I'm using Javascript to remove some of them (this.parentNode.removeChild(this)) which is working great. However, if I have a variable referring to this node, then remove the node, the variable does NOT lose it's value! But if I then try and perform some other actions on this element, I get errors!

Example:

var element = document.getElementById('ooolookatmeimanelement');
element.parentNode.removeChild(element);
alert(element);

I still get "[Object HTMLblahblahblah]" in the alert, rather than null or undefined - anyone got any ideas how I can check to see if the node has been removed? It's probably something really simple that I'm oblivious to!

like image 266
HughieW Avatar asked Sep 13 '25 09:09

HughieW


1 Answers

If you remove the node, remove the references too. E.g. in your code, assign null to element:

element = null;

Or if this is not possible, you can always check the value of parentNode. It should give null if the element is not part of the DOM:

if(element.parentNode === null) {
    // element is not part of the DOM
}

But this does not make much sense to me (might depend on the context though): If you removed an element, then you know that you have removed it. Why would you do any further operations on it?

like image 84
Felix Kling Avatar answered Sep 15 '25 00:09

Felix Kling