tags:

views:

46

answers:

4

Let's say that I define an element

$foo = $('#foo');

and then I call

$foo.remove()

from some event. My question is, how do I check whether $foo has been removed from the DOM or not? I've found that $foo.is(':hidden') works, but that would of course also return true if I merely called $foo.hide().

+3  A: 

I just realized an answer as I was typing my question: Call

$foo.parent()

If $f00 has been removed from the DOM, then $foo.parent().length === 0. Otherwise, its length will be at least 1.

[Edit: This is not entirely correct, because a removed element can still have a parent; for instance, if you remove a <ul>, each of its child <li>s will still have a parent. Use SLaks' answer instead.

Trevor Burnham
... unless the removed node was not an only child
Álvaro G. Vicario
@Álvaro - Why would that matter?
patrick dw
@patrick: Did I miss something? What can you assure if $foo.parent().length is greater than zero?
Álvaro G. Vicario
@Álvaro - the OP is testing to make sure `$foo` was removed from the DOM. If it was successfully removed, it will no longer have a parent element. Therefore `$foo.parent().length === 0` means that the removal was successful.
patrick dw
@patrick: Oh my... Now I get it!
Álvaro G. Vicario
+4  A: 

Like this:

if (!$foo.closest('html').length) {
    //Element is detached
}

This will still work if one of the element's parents was removed (in which case the element itself will still have a parent).

SLaks
+1  A: 

You can check whether your selector actually matches something:

if($('#foo').length==0){
    // Element is gone
}

Depending on your exact code, you may not need to use .length anyway: jQuery basically ignores empty collections.

Edit

As macek points out, $foo.length does not change even if you remove one of the matched nodes. If you re-run the original query ($('#foo').length rather than $foo.length) it seems that you get an updated collection (althoug I can't assure that's true in all cases).

Álvaro G. Vicario
Álvaro, in his question, `$foo` is then then `.remove()` is called. At this point, `$foo.length == 1` even though the element has been removed.
macek
You are right: if you store the matched items collections into a variable, the variable doesn't change when you remove one of the items.
Álvaro G. Vicario
A: 

Since foo.remove() will always work if foo matches any element(s), you could test foo.length before issuing the .remove() statement.

macek