Example 1 — Official: Count Divs on Click
Append a div, then show $("div").length.
$(document.body)
.on("click", function () {
$(document.body).append($(""));
var n = $("div").length;
$("span").text(
"There are " + n + " divs. Click to add more."
);
})
.trigger("click"); How It Works
- Click. Handler appends a new
<div>. - Count.
$("div").length reads the match total. - Show. Update the span text with
n.
Example 2 — Empty Set Returns 0
Missing selectors do not throw — they count as zero.
jQuery var n = $("#does-not-exist").length;
$("#out").text("Matches: " + n);
How It Works
- Select. Query an id that is not on the page.
- Read.
.length is 0. - Safe. No error — empty collections are normal in jQuery.
Example 3 — Count Inside a Container
Scope the selector so you only count children you care about.
jQuery var n = $("#list li").length;
$("#out").text("List items: " + n);
How It Works
- Scope.
#list li matches only items under #list. - Count.
.length returns how many li matched. - Show. Print the integer in the output.
Frequently Asked Questions
Next: Tutorial for Beginners: What Is jQuery?
Learn how selections are built — then count them with .length.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
9 people found this page helpful

