gavsiu
gavsiu

Reputation: 757

JQuery: Check if element exists alongside '.remove()'

I know you can check if an element exists with $('div').length, but when an element is destroyed using .remove(), .length still reports the div exists. How can I find whether or not it actually exists?

if ($('div').length) { 
  alert('yes') 
} else { 
  alert('no') 
}

Upvotes: 14

Views: 26746

Answers (4)

user1444978
user1444978

Reputation: 124

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).

I cite this answer.

Upvotes: 4

Ehtesham
Ehtesham

Reputation: 2985

you can get the parent of element before removing the element and after the element has been removed you can check like this!

    var parent = $(element).parent();
    $(element).remove();

    if(parent.children(element)) {  alert('yes'); }
    else { alert('no'); }

of course element would be some jquery selector

Upvotes: 0

gilly3
gilly3

Reputation: 91557

By exists, you mean you want to see if it exists in the dom? Check to see if "html" is an ancestor:

var $myDiv = $(".myDiv");
$myDiv.closest("html").length;  // returns 1
$myDiv.remove();
$myDiv.closest("html").length;  // returns 0

Or use .is("html *"). It returns a boolean, which is handy:

var $myDiv = $(".myDiv");
$myDiv.is("html *"); // returns true
$myDiv.remove();
$myDiv.is("html *"); // returns false

Upvotes: 9

Felix Kling
Felix Kling

Reputation: 816780

Test whether it has a parent:

if ($element.parent().length) { alert('yes') }
else { alert('no') }

or if you have a reference to the DOM element:

if(element.parentNode) {
    // yes
}

Obviously, this only works for elements you already have a reference to.

FWIW, the element itself still exists, it is just not part of the DOM tree.

Upvotes: 7

Related Questions