How to Check if a jQuery Object Is Empty
When selecting elements with jQuery, the function always returns a
jQuery object, even if no matching DOM elements exist on the page.
Because this returned object is always truthy, standard JavaScript
existence checks like if ($('.my-class')) will not work as
expected. This article explains how to accurately determine if a jQuery
collection contains zero elements using the .length
property, native array indexing, and custom helper methods, while
clarifying common misconceptions around jQuery's :empty
selector.
The Standard
Method: Checking the .length Property
The most efficient and idiomatic way to verify whether a jQuery
selection matched any elements is by inspecting its .length
property. A jQuery object behaves like an array; its length
reflects the exact number of matched DOM elements.
if ($('#my-element').length === 0) {
console.log('The jQuery object is completely empty.');
} else {
console.log('Element exists in the DOM.');
}You can also use a direct truthiness evaluation on the length:
if (!$('.items').length) {
// Executes if no elements with class "items" were found
}The Array Index Method
Because jQuery objects are array-like structures wrapping DOM nodes,
you can directly access the underlying DOM element at index
0. If the selection found no elements, index 0
returns undefined.
if ($('#my-element')[0] === undefined) {
console.log('No elements matched.');
}
// Alternatively, using loose falsy evaluation:
if (!$('#my-element')[0]) {
console.log('No elements matched.');
}This method is functionally equivalent to checking
.length === 0 and carries minimal performance overhead
since it accesses the property directly without invoking extra
methods.
The :empty
Selector Misconception
A common mistake is attempting to use jQuery’s
.is(':empty') method to test for an empty collection.
// INCORRECT for checking if a selection matched nothing
if ($('.my-class').is(':empty')) {
// This checks if the matched elements have no child nodes or text,
// NOT whether the jQuery object itself has zero matched elements.
}The :empty pseudo-class checks whether the matched DOM
elements themselves contain text or child elements. If the jQuery
selector matches zero elements in the first place,
.is(':empty') returns false, which can lead to
misleading logic. Always use .length instead.
Creating a Reusable Helper Method
If your codebase requires frequent checks and you prefer a more readable syntax, you can extend jQuery's prototype by creating a custom plugin method:
$.fn.isEmpty = function() {
return this.length === 0;
};
// Usage:
if ($('.notification-banner').isEmpty()) {
console.log('No banners found.');
}Checking that .length === 0 remains the fastest, most
reliable, and standard approach across all versions of jQuery.