jQuery .length Property

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Match count

What You’ll Learn

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

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.

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.

📝 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");
}

⚡ Quick Reference

TopicDetail
AddedjQuery 1.0
RemovedNever — still in jQuery 3.7.x
TypeInteger (element count)
Access$(...).length
Empty selection0 — no exception
Legacy equivalent.size() — removed in 3.0
First elementcollection[0] or .get(0)
Truthy checkif ($(".x").length)

📋 .length vs .size() vs .selector

Three collection facts — one essential today, one removed method, one removed property.

.length
3

Current count — use this

.size()
removed

Same value — jQuery 3.0

.selector
removed

Query string — not count

.jquery
"3.7.1"

Version — not count

Examples Gallery

Example 1 adapts the official jQuery demo. All examples use jQuery 3.7.1.

📚 Getting Started

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");
Try It Yourself

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
Try It Yourself

How It Works

More specific selectors usually yield smaller .length values. Always read .length on the exact collection you plan to manipulate.

Example 3 — Zero Matches Without Errors

Missing elements produce an empty collection — .length is 0, not undefined.

jQuery
console.log($("#does-not-exist").length); // 0
console.log($().length);                  // 0

if (!$("#banner").length) {
  console.log("No banner on this page — skip setup");
}
Try It Yourself

How It Works

jQuery’s empty collections are safe to chain — most methods no-op gracefully. Checking .length first avoids pointless work.

Example 4 — .length After .filter() and .add()

Unlike .selector, the count updates to match the current set.

jQuery
var $all = $(".tag");              // 4
var $active = $all.filter(".active"); // 2
var $more = $active.add($("<span>", { "class": "tag active" }));
console.log($more.length);            // 3
Try It Yourself

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)";
}
Try It Yourself

How It Works

if (!$cards.length) is clearer than try/catch for missing DOM. Combine with early return to keep widget init code readable.

🚀 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.

📝 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.

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.

Universal All jQuery versions
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
jQuery 3.7.x support Supported

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.

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.

💡 Best Practices

✅ Do

  • Use .length for existence checks before .each()
  • 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)

Key Takeaways

Knowledge Unlocked

Five things to remember about .length

Element count — live, zero-safe, still essential in 3.x.

5
Core concepts
0 02

Empty OK

No throw

Safe
.filter 03

Updates

Live count

Chain
if 04

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.

Next: jQuery Selectors

Learn CSS selector syntax — what you pass to $() before reading .length.

Selectors tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful