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!
E开发者_Go百科xample:
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!
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?
You can also use document.body.contains(element)
; or $.contains(body, element)
.
Checking for the parentNode
is not reliable; if what is removed is an ancestor of the element, instead of the element itself, then parentNode
will still return the parent, while the element is not in the DOM anymore.
var ancestor = document.querySelector('div');
var ghost = document.querySelector('br');
ancestor.parentNode.removeChild(ancestor);
console.log(ghost.id + ' son of ' + ghost.parentNode.id);
console.log(ghost.id + (document.body.contains(ghost) || ' dont') + ' exists in DOM');
<div id="ancestorToRemove">
<p id="a bitch">
<br id="you">
</p>
</div>
.removeChild()
only removes the element from the DOM, and not from memory.
Hence it still exists until it's garbage collected. However you're holding a reference to it, so that won't happen.
Another point that may save time if you're needing to run JavaScript triggered by onClick
which does something to itself, you can do this:
onClick="if(!document.getElementById(this.id))return false; YOUR CODE HERE"
For me, this came up when I had a DIV
with several children, one of which was a "remove this div" button (actually a DIV
made to look like a button). When clicked, this 'button' would remove the DIV
from the DOM, as expected, but then would call the onClick event of the DIV
itself (which no longer exists). This caused problems. By adding this to my DIV
's onClick
, I prevented running the code which refers to the DIV
after its removal.
精彩评论