How do I check whether a jQuery element is in the DOM?

后端 未结 11 1919
我寻月下人不归
我寻月下人不归 2020-11-28 04:46

Let\'s say that I define an element

$foo = $(\'#foo\');

and then I call

$foo.remove()

from some event. My

11条回答
  •  广开言路
    2020-11-28 05:30

    instead of iterating parents you can just get the bounding rect which is all zeros when the element is detached from dom

    function isInDOM(element) {
        var rect=element.getBoundingClientRect();
        return (rect.top || rect.bottom || rect.height || rect.width)?true:false;
    }
    

    if you want to handle the edge case of a zero width and height element at zero top and zero left you can double check by iterating parents till the document.body

提交回复
热议问题