Check if object is a jQuery object
You can use the instanceof
operator:
if (obj instanceof jQuery){
console.log('object is jQuery');
}
Explanation: the jQuery
function (aka $
) is implemented as a constructor function. Constructor functions are to be called with the new
prefix.
When you call $(foo)
, internally jQuery translates this to new jQuery(foo)
1. JavaScript proceeds to initialize this
inside the constructor function to point to a new instance of jQuery
, setting it's properties to those found on jQuery.prototype
(aka jQuery.fn
). Thus, you get a new
object where instanceof jQuery
is true
.
1It's actually new jQuery.prototype.init(foo)
: the constructor logic has been offloaded to another constructor function called init
, but the concept is the same.
How to detect is argument jQuery object
Use the typeof
operator
if ( typeof value === 'string' ) {
// it's a string
} else {
// it's something else
}
Or to make really sure it's an instance of the jQuery object
if ( typeof value === 'string' ) {
// it's a string
} else if ( value instanceof $) {
// it's a jQuery object
} else {
// something unwanted
}
How to check if an object is a jQuery event
Agreeing @Rocket's comment: instanceof
is the way to go. You can try this on SO's website in the JS console
var x = $.Event()
x instanceof $.Event
More information can be found in this eerily similar post: https://stackoverflow.com/a/1853246/1883547
jQuery - check if variable is dom element
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>
Is there an exists function for jQuery?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0
means false
, everything else true
. So you could write:
if ($(selector).length)
You don't need that >0
part.
How to know an object is jQuery object or not
Use instanceof
:
console.log(elm instanceof jQuery);
or:
console.log(elm instanceof $);
Demo: http://jsfiddle.net/karim79/8jUKX/
Check if JQuery object exists in DOM
If performance is a really big concern for you, native methods are generally the way to go.
document.contains($myJQueryEl[0])
Outperforms the next fastest jQuery operation, $elem.closest('body')
, by around 4 times according to this answer and its comment.
If you're really looking for performance for non-document elements, however, Shadow DOM is definitely your best option.
Determine if a variable is an empty jquery object
$targetSection.length
will be zero if no matching selector is found.
How can I determine if a jQuery object is deferred?
Depending on your use case, you could also use jQuery.when
[1]:
If a single argument is passed to
jQuery.when
and it is not a Deferred, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.
With jQuery.when
you can treat your mysterious object always as deferred:
// x could be a deferred object or an immediate result
var x = getMysteriousObject();
// success will be called when x is a deferred object and has been resolved
// or when x is an immediate result
jQuery.when( x ).then( success, error );
[1] http://api.jquery.com/jQuery.when/
How do I check if a variable is a jQuery object or plain DOM element?
- A jquery object has a
jquery
property. - A jquery object is an
instanceof jQuery
(instanceof
on MDN) - A DOM element has a
nodeType
property
Related Topics
Why Do We Need to Install Gulp Globally and Locally
JavaScript Runtime Complexity of Array Functions
How to Make API Call with Hooks in React
Jasmine: Async Callback Was Not Invoked Within Timeout Specified by Jasmine.Default_Timeout_Interval
How to Display Binary Data as Image in React
How to Define Setter/Getter on Prototype
How to Stop a Page from Unloading (Navigating Away) in Js
How to Get All Options of a Select Using Jquery
How to Print a Stack Trace in Node.Js
How to Call Fromlatlngtodivpixel in Google Maps API V3
JavaScript Settimeout() Won't Wait to Execute
React Router Doesn't Work in Aws S3 Bucket
Using Number as "Index" (JSON)
Add Onclick Event to Newly Added Element in JavaScript