gavsiu gavsiu - 14 days ago 5
jQuery Question

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

Answer

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.