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

后端 未结 11 1859
我寻月下人不归
我寻月下人不归 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:11

    Probably the most performative way is:

    document.contains(node); // boolean
    

    This also works with jQuery:

    document.contains($element[0]); // var $element = $("#some-element")
    document.contains(this[0]); // in contexts like $.each(), `this` is the jQ object
    

    Source from MDN

    Note:

    • Internet Explorer only supports contains() for elements.
    0 讨论(0)
  • 2020-11-28 05:11

    Agree with Perro's comment. It can also be done like this:

    $foo.parents().last().is(document.documentElement);
    
    0 讨论(0)
  • 2020-11-28 05:11
    jQuery.fn.isInDOM = function () {
       if (this.length == 1) {
          var element = this.get(0);
          var rect = element.getBoundingClientRect();
          if (rect.top + rect.bottom + rect.width + rect.height + rect.left + rect.right == 0)
             return false;
          return true;
       }
       return false;
    };
    
    0 讨论(0)
  • 2020-11-28 05:13

    Why not just: if( $('#foo').length === 0)... ?

    0 讨论(0)
  • 2020-11-28 05:16
    if($foo.nodeType ){ element is node type}
    
    0 讨论(0)
  • 2020-11-28 05:17

    How about doing this:

    $element.parents('html').length > 0
    
    0 讨论(0)
提交回复
热议问题