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

gavsiu picture gavsiu · Jul 16, 2011 · Viewed 21.6k times · Source

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') 
}

Answer

Felix Kling picture Felix Kling · Jul 16, 2011

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.