Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  17] [ 5]  / answers: 1 / hits: 15969  / 13 Years ago, mon, march 21, 2011, 12:00:00

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!


More From » dom

 Answers
23

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?


[#93165] Saturday, March 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
halleyb

Total Points: 604
Total Questions: 96
Total Answers: 115

Location: Tokelau
Member since Wed, Oct 14, 2020
4 Years ago
;