开发者

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

开发者 https://www.devze.com 2023-03-20 21:32 出处:网络
I know you can check if an element exists with $(\'di开发者_如何学Cv\').length, but when an element is destroyed using .remove(), .length still reports the div exists. How can I find whether or not it

I know you can check if an element exists with $('di开发者_如何学Cv').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') 
}


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


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消