The .length property tells you how many DOM elements are in a jQuery collection right now. This tutorial covers the official click-to-count demo, empty-set behavior, how .length changes after .filter(), comparing it with removed .size(), and guard patterns before .each() loops.
01
Integer
Count
02
Since 1.0
Added
03
Zero OK
No error
04
Live
Current set
05
Not .size()
Removed 3.0
06
3.7.x
Still works
Fundamentals
Introduction
Every time you call $("div"), jQuery returns a collection object — not a single element, but a list of everything that matched. The .length property answers the first question beginners ask: how many?
If three paragraphs match, $("p").length is 3. If nothing matches, it is 0 — jQuery does not throw an error. That makes .length perfect for guards like if ($(".alert").length) { ... } before you update the page.
Unlike legacy properties such as .selector, .length always describes the current collection. After .filter(), .add(), or .not(), read .length again and you get the updated count.
Concept
Understanding the .length Property
.length is a non-negative integer on jQuery collections. It counts DOM element references stored in the jQuery object’s internal array-like structure — the same count you would get from indexing [0], [1], … up to [length - 1].
jQuery collections are array-like, not true JavaScript arrays. They expose .length and numeric indexes, but methods like .push() are not available — you use jQuery methods to change membership instead.
💡
Use .length, not .size()
The old .size() method returned the same number but was deprecated in jQuery 1.8 and removed in jQuery 3.0. Modern code always reads .length.
Foundation
📝 Syntax
Read the property on any jQuery collection — no parentheses:
jQuery
jQueryCollection.length
Return value
A non-negative Integer — number of elements currently in the set.
0 when the selector matched nothing or the set is empty $().
Updates when chaining returns a new collection with different membership.
Read-only — assign to .length does not add or remove DOM nodes.
Common guard pattern
jQuery
var $items = $(".cart-item");
if ($items.length) {
$items.addClass("in-cart");
}
Cheat Sheet
⚡ Quick Reference
Topic
Detail
Added
jQuery 1.0
Removed
Never — still in jQuery 3.7.x
Type
Integer (element count)
Access
$(...).length
Empty selection
0 — no exception
Legacy equivalent
.size() — removed in 3.0
First element
collection[0] or .get(0)
Truthy check
if ($(".x").length)
Compare
📋 .length vs .size() vs .selector
Three collection facts — one essential today, one removed method, one removed property.
Count elements in a live collection — the official interactive pattern.
Example 1 — Count Divs on Click (Official Demo)
Click the page to append a div, then read $("div").length to update the message.
jQuery
$(document.body).on("click", function () {
$(document.body).append($("<div>"));
var n = $("div").length;
$("span").text("There are " + n + " divs. Click to add more.");
}).trigger("click");
There are 1 divs. Click to add more.
(each click increments the count)
How It Works
Every new div increases the global $("div").length because the selector re-runs against the updated DOM. The property always reflects how many divs exist now.
📈 Practical Patterns
Scoped counts, empty sets, filtered collections, and pre-loop guards.
Example 2 — Count After a Selector
Read .length immediately after selecting — compare scoped vs broader queries.
jQuery
console.log($("#menu .item").length); // 3
console.log($("#menu li").length); // 4 — includes non-.item li
All .tag: 4
After .filter('.active'): 2
After .add(new span): 3
How It Works
Each chained method returns a new jQuery object pointing at a different subset. Always read .length on the variable holding the collection you care about.
Example 5 — Guard Before .each() or DOM Updates
Skip plugin logic when nothing matched — idiomatic production pattern.
jQuery
function highlightCards(selector) {
var $cards = $(selector);
if (!$cards.length) {
return "No cards matched: " + selector;
}
$cards.css("border", "2px solid #2563eb");
return "Highlighted " + $cards.length + " card(s)";
}
if (!$cards.length) is clearer than try/catch for missing DOM. Combine with early return to keep widget init code readable.
Applications
🚀 When You Use .length
Existence checks — run code only when $(".widget").length is truthy.
UI counters — display “3 items selected” from $(".selected").length.
Validation — require at least one checked checkbox before submit.
Debugging — log match counts after complex selectors in DevTools.
Plugin init — bail out early when the target elements are absent.
After chaining — confirm .filter() narrowed the set as expected.
🧠 How jQuery Tracks .length
1
Selector or wrap runs
jQuery gathers DOM node references into an internal list.
Query
2
Set .length
The integer equals how many nodes were stored — may be 0.
Count
3
Chain methods
New collections get their own .length — filter, add, not, find.
Update
4
✅
Read anytime
Property reflects the collection you hold — stable API since 1.0.
Important
📝 Notes
Added in jQuery 1.0 — one of the core collection properties.
.size() returned the same value; deprecated 1.8, removed 3.0.
Access first element with $(".x")[0] or $(".x").get(0) — not .length.
.length counts elements, not characters — unlike string .length in JavaScript.
Related property: .jquery — version string, not element count.
Empty jQuery objects are truthy in JavaScript — use .length, not if ($()).
For plain arrays, use array.length; for jQuery collections, use the same property name on the $ result.
Compatibility
Browser Support
.length works wherever jQuery runs. It has been available since jQuery 1.0 and remains fully supported in jQuery 3.7.x.
✓ Since 1.0
jQuery .length
Universal across all jQuery 1.x, 2.x, and 3.x releases. Prefer .length over the removed .size() method in every environment.
UniversalAll jQuery versions
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
jQuery 3.7.x supportSupported
Bottom line: .length is the essential collection property beginners use daily — it survived every jQuery major release because match count is fundamental to DOM work.
Wrap Up
Conclusion
.length is the simplest and most useful jQuery collection property: it tells you how many elements you matched. Zero means nothing found — no error. After filtering or adding elements, read it again for the updated count.
Replace any legacy .size() calls with .length, and use if ($(".target").length) before loops or DOM updates. Together with .jquery for version checks, .length is one of the two property reads every jQuery beginner should memorize.
Read .length on the specific collection variable you chained
Display user-facing counts from $(".item").length
Replace legacy .size() with .length when upgrading
Combine with .eq() and .get() for indexed access
❌ Don’t
Use .size() in jQuery 3.x — it was removed
Assign to .length expecting to resize the collection
Confuse jQuery .length with string character count
Assume a jQuery object is falsy when empty — check .length
Use .length to get the first element — use [0] or .get(0)
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about .length
Element count — live, zero-safe, still essential in 3.x.
5
Core concepts
#01
Integer
Match count
Type
002
Empty OK
No throw
Safe
.filter03
Updates
Live count
Chain
if04
Guard
Before .each
Pattern
≠05
.size()
Removed
Legacy
❓ Frequently Asked Questions
.length is a read-only number on every jQuery collection. It returns how many DOM elements are currently in the set — for example $("li").length might return 5. Added in jQuery 1.0 and still supported in jQuery 3.7.x.
It returns 0. jQuery does not throw an error for empty selections — $("#missing").length is 0. This makes if ($(".item").length) a common guard before running loops or updates.
Yes — they returned the same integer. .size() was deprecated in jQuery 1.8 and removed in jQuery 3.0. Always use .length in modern code.
Yes. Unlike removed metadata like .selector, .length always reflects the current collection. $(".tag").filter(".active").length counts only the filtered subset.
Same idea — a numeric count — but jQuery .length counts DOM elements in the collection, not arbitrary array slots. jQuery objects are array-like: you can index [0] for the first element and read .length for the total.
Use .length for a quick boolean check: if ($(".warn").length) { ... }. Use .each() when you need to visit every matched element. Checking .length first avoids unnecessary iteration on empty sets.
Did you know?
jQuery collections borrow the familiar .length name from JavaScript arrays so beginners can iterate with numeric indexes immediately. Under the hood jQuery stores DOM references in an array-like object and keeps .length in sync when chaining methods return new subsets. That is why .length stayed while .selector was removed — element count is always accurate and always useful; the original query string was not.