What Is the jQuery .length Property Used For?
This article provides a comprehensive overview of the jQuery
.length property, explaining its core function, primary use
cases, and best practices. In jQuery, .length is a built-in
property that returns the number of DOM elements contained within a
jQuery collection. By reading on, you will learn how to use this
property to count elements, verify whether an element exists on a
webpage before manipulating it, and avoid common pitfalls when working
with conditional statements in JavaScript.
Core Function of
.length
When you select elements using jQuery (for example,
$('p')), jQuery returns an array-like object containing all
matching DOM elements. The .length property simply holds an
integer representing the total count of elements inside that collection.
If no matching elements are found, .length evaluates to
0.
// Counts all paragraph tags on the page
let paragraphCount = $('p').length;
console.log(paragraphCount);Checking If an Element Exists
The most common practical application of .length is
verifying an element's existence in the DOM. Because jQuery always
returns an object—even if no matching elements are found—a standard
truthiness check like if ($('.my-element')) will always
evaluate to true.
To reliably determine if an element is present, you must check the
.length property:
// Correct way to check for element existence
if ($('#submit-button').length) {
// Executes only if the element exists in the DOM
$('#submit-button').addClass('active');
}Because 0 is a falsy value in JavaScript,
$('#submit-button').length evaluates to false
when no match is found, and any positive integer evaluates to
true. You can also write this explicitly as
$('#submit-button').length > 0.
Counting Elements and Form Validation
The .length property is also widely used for tallying
items and validating user input. Common scenarios include:
- List counting: Checking how many items are
currently in an unordered list
(
$('ul.todos li').length). - Form validation: Ensuring a user has selected at
least one checkbox
(
$('input[type="checkbox"]:checked').length). - Dynamic content checks: Determining whether dynamically loaded cards, rows, or modal windows are currently rendered on the screen.
.length vs.
.size()
Older jQuery codebases frequently used the .size()
method to achieve the same result. However, .size() was
deprecated in jQuery 1.8 and entirely removed in jQuery 3.0. The
.length property is preferred because it reads directly
from an internal property rather than requiring an extra function call,
making it faster and fully compatible with modern jQuery versions.