How can I check the existence of an element in jQuery?
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
<
I have found if ($(selector).length) {}
to be insufficient. It will silently break your app when selector
is an empty object {}
.
var $target = $({});
console.log($target, $target.length);
// Console output:
// -------------------------------------
// [▼ Object ] 1
// ► __proto__: Object
My only suggestion is to perform an additional check for {}
.
if ($.isEmptyObject(selector) || !$(selector).length) {
throw new Error('Unable to work with the given selector.');
}
I'm still looking for a better solution though as this one is a bit heavy.
Edit: WARNING! This doesn't work in IE when selector
is a string.
$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE