Adam Pietrasiak
Adam Pietrasiak

Reputation: 13194

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?

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

Upvotes: 8

Views: 5554

Answers (2)

War10ck
War10ck

Reputation: 12508

You can use instanceof to check if the object passed in is an instanceof jQuery or an instanceof HTMLElement. If it is return true;. Otherwise, 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. 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. 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. 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.

EDIT:

An additional edit was made per @AdamPietrasiak's comment below regarding instances of HTMLCollections returning false. In this case, if the obj passed in is an instance of HTMLCollection, each element is passed to the internal checkInstance function. 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 (i.e. for instances of HTMLCollection the function treats it as an all or nothing).

Upvotes: 9

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

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>

Upvotes: 4

Related Questions