You can use instanceof to check if an object passed in instanceof jQuery or 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 can perform another action. You can also separate each option and perform a separate action, depending on which object is an instance of jQuery or HTMLElement . You have a choice 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 relevant point regarding a function that returns a jQuery instance without matched elements. For this reason, I updated the function to take into account not only if the object is a jQuery instance, but also if the object has a length, indicating whether a DOM element was found.
EDIT:
Regarding the @AdamPietrasiak comment below, additional editing has been added regarding instances of HTMLCollections returning false. In this case, if the passed obj is an instance of an HTMLCollection , each element is passed to the checkInstance internal function. Any element that is not a DOM node runs a function to generate a common false , regardless of whether the element was in the list (i.e., for HTMLCollection instances HTMLCollection function considers it as all or nothing).
source share