简体   繁体   English

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

[英]jQuery - check if variable is dom element

Is there any way to check if given variable is not-empty jQuery object or native DOM element? 有没有办法检查给定变量是不是空的 jQuery对象还是本机DOM元素?

so it would be like 所以它会是这样的

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... 

You can use instanceof to check if the object passed in is an instanceof jQuery or an instanceof HTMLElement . 您可以使用instanceof来检查传入的对象是instanceof jQueryinstanceof HTMLElementinstanceof HTMLElement If it is return true; 如果是return true; . Otherwise, return false . 否则, 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;        
      }
}

Optionally, instead of returning true or false , you could do some other action. (可选)您可以执行其他操作,而不是返回truefalse You could also split each option out and do a separate action depending on which one the object is an instance of jQuery or HTMLElement . 您还可以将每个选项拆分出来并执行单独的操作,具体取决于该对象是jQueryHTMLElement的实例。 You have lots of choices to choose from. 您有很多选择可供选择。

 $(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; } } }); 
 <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> 

EDIT: 编辑:

@RickHitchcock made a very valid point regarding the function returning an instance of jQuery with no matched elements. @RickHitchcock就返回没有匹配元素的jQuery实例的函数提出了一个非常有效的观点。 For this reason, I've updated the function to take into account not only if the object is an instanceof jQuery but also if the object has a length, indicating whether a DOM element was found. 出于这个原因,我已经更新了函数,不仅要考虑对象是jQuery的实例,还要考虑对象是否有长度,指示是否找到了DOM元素。

EDIT: 编辑:

An additional edit was made per @AdamPietrasiak 's comment below regarding instances of HTMLCollections returning false. 关于HTMLCollections返回false的实例,下面根据@AdamPietrasiak的评论进行了额外的编辑。 In this case, if the obj passed in is an instance of HTMLCollection , each element is passed to the internal checkInstance function. 在这种情况下,如果传入的objHTMLCollection的实例,则每个元素都将传递给内部checkInstance函数。 Any element which is not a DOM node triggers the function to throw an overall false regardless of whether there was an element in the list (ie for instances of HTMLCollection the function treats it as an all or nothing). 任何不是DOM节点的元素都会触发函数抛出整体false无论列表中是否有元素(例如,对于HTMLCollection的实例,函数将其视为全部或全部)。

I think this covers all cases: 认为这包括所有情况:

 console.clear(); function isDomElem(el) { return el instanceof HTMLElement || el[0] instanceof HTMLElement ? true : false; } console.log(isDomElem($("#some-existing-element"))); //returns true console.log(isDomElem($("#some-existing-element")[0])); //returns true console.log(isDomElem($("#non-existing-element"))); //returns false console.log(isDomElem("#some-existing-element")); //returns false console.log(isDomElem([0,1,2])); //returns false console.log(isDomElem(document.getElementsByClassName("a"))); //returns true 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="some-existing-element" class="a"></div> <div class="a"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM