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

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

    Since I'm unable to respond as a comment (too low karma I guess), here's a full reply. The fastest way is easily to unroll the jQuery check for browser support and to shave the constant factors to minimum.

    As seen also here - http://jsperf.com/jquery-element-in-dom/28 - the code would look like this:

    var isElementInDOM = (function($) {
      var docElt = document.documentElement, find,
          contains = docElt.contains ?
            function(elt) { return docElt.contains(elt); } :
    
            docElt.compareDocumentPosition ?
              function(elt) {
                return docElt.compareDocumentPosition(elt) & 16;
              } :
              ((find = function(elt) {
                  return elt && (elt == docElt || find(elt.parentNode));
               }), function(elt) { return find(elt); });
    
      return function(elt) {
        return !!(elt && ((elt = elt.parent) == docElt || contains(elt)));
      };
    })(jQuery);
    

    This is semantically equivalent to jQuery.contains(document.documentElement, elt[0]).

提交回复
热议问题