jQuery - 检查变量是否为dom元素

pie*_*e6k 5 javascript jquery dom

有没有办法检查给定变量是不是空的 jQuery对象还是本机DOM元素?

所以它会是这样的

isDomElem( $("#some-existing-element") ); //returns true
isDomElem( $("#some-existing-element")[0] ); //returns true
isDomElem( $("#non-existing-element")[0] ); //returns false
isDomElem( "#some-existing-element" ); //returns false
isDomElem( [0,1,2] ); //returns false
//etc... 
Run Code Online (Sandbox Code Playgroud)

War*_*0ck 5

您可以instanceof用来检查传入的对象是一个instanceof jQuery还是一个instanceof HTMLElement.如果是的话return true;.否则,return false.

function isDomElem(obj) {
      if(obj instanceof HTMLCollection && obj.length) {
          for(var a = 0, len = obj.length; a < len; a++) {
              if(!checkInstance(obj[a])) {
                  console.log(a);
                  return false;   
              }
          }     
          return true;                
      } else {
          return checkInstance(obj);  
      }

      function checkInstance(elem) {
          if((elem instanceof jQuery && elem.length) || elem instanceof HTMLElement) {
              return true;  
          }
          return false;        
      }
}
Run Code Online (Sandbox Code Playgroud)

可选的,而不是返回true或者false,你可以做一些其他的动作.你也可以拆分每个选项走出去,做一个依赖单独行动上哪一个对象的实例jQueryHTMLElement.您有很多选择可供选择.

$(function () {
  var temp1 = $('div'),
      temp2 = $('div')[0],
      temp3 = "foo",
      temp4 = ['bar'],
      temp5 = $('span'),
      temp6 = document.getElementsByClassName("test");
  
  alert(isDomElem(temp1));
  alert(isDomElem(temp2));
  alert(isDomElem(temp3));
  alert(isDomElem(temp4));
  alert(isDomElem(temp5));
  alert(isDomElem(temp6));
  
  function isDomElem(obj) {
    
      if(obj instanceof HTMLCollection && obj.length) {
        
        for(var a = 0, len = obj.length; a < len; a++) {
            if(!checkInstance(obj[a])) {
                return false;   
            }
        }
               
        return true;
               
      } else {
          return checkInstance(obj);  
      }
        
      function checkInstance(elem) {
          if((elem instanceof jQuery && elem.length) || elem instanceof HTMLElement) {
              return true;  
          }
          return false;        
      }
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<p class="test"></p>
<p class="test"></p>
Run Code Online (Sandbox Code Playgroud)

编辑:

@RickHitchcock就返回没有匹配元素的jQuery实例的函数提出了一个非常有效的观点.出于这个原因,我已经更新了函数,不仅要考虑对象是jQuery的实例,还要考虑对象是否有长度,指示是否找到了DOM元素.

编辑:

根据@AdamPietrasiak关于HTMLCollections返回false的实例的评论进行了额外的编辑.在这种情况下,如果obj传入的是一个实例HTMLCollection,则每个元素都传递给内部checkInstance函数.任何不是DOM节点的元素都会触发函数抛出整体,false无论列表中是否有元素(即HTMLCollection函数的实例将其视为全部或全部).