Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 56 ยท Selecting Elements

Selector Performance and Caching

Learn how to make jQuery selectors fast: cache jQuery objects, narrow the search with context and .find(), avoid over-qualified selectors and measure with console.time.

Every time you write $(".item"), jQuery has to search the document. On a small page that takes a fraction of a millisecond and nobody notices. On a page with thousands of nodes, or inside a loop or a scroll handler that fires dozens of times per second, repeated searches add up. The good news is that a handful of simple habits remove almost all of the waste, and none of them make your code harder to read.

This lesson covers the habits that matter: caching the result of a selection, narrowing the search to a part of the page, writing selectors that the browser can answer quickly, and measuring instead of guessing. It builds on basic selectors and the jQuery object.

Four habits for fast selectors

Cache Select once, reuse the variable.
Narrow Search inside a parent, not the whole page.
Be direct An id or a plain class beats a long chain.
Measure Time it before you optimize it.
1 / 2

What a selection costs

A selector string is parsed, matched against the document and wrapped in a new jQuery object. For simple selectors such as #id, .class or tag, jQuery hands the work to fast native browser functions (getElementById, getElementsByClassName, querySelectorAll). The cost then grows with the number of nodes the browser has to inspect, and the wrapper object is created again on every call.

So there are two separate costs: finding the elements and wrapping them. Caching removes both, because you keep the finished jQuery object.

Cache jQuery objects

If you use the same selection more than once, store it in a variable. A common convention is to start the variable name with $ so you can tell at a glance that it holds a jQuery object.

JavaScript
// Wasteful: three searches for the same elements
$(".price").addClass("highlight");
$(".price").css("color", "crimson");
$(".price").fadeIn();

// Better: one search
const $prices = $(".price");
$prices.addClass("highlight").css("color", "crimson").fadeIn();

The second form also shows the other cure for repeated lookups: chaining. When all the calls act on the same set, one chain does the job with a single search.

Caching matters most in loops and event handlers. Anything that does not change between iterations belongs outside the loop. The next example counts how many times each style of code searches the document. Each button click runs a loop of 500 steps.

Counting searches: uncached versus cached

Notice that the cached version still calls .eq(i) 500 times. That is fine: .eq() works on a collection you already have, so it does not search the document.

Caching has one catch

A cached jQuery object is a snapshot. If elements are added to the page later, the variable does not grow. When the page changes, either re-select, or delegate your events so you do not need to hold on to the elements at all.

Narrow the search with .find() and context

Searching the whole document is the most expensive way to look. If you already have a container, search only inside it.

JavaScript
const $cart = $("#cart");              // one fast lookup by id

const $rows  = $cart.find(".row");     // search only inside #cart
const $total = $cart.find(".total");

The second argument of $() is a context: $(".row", $cart) means the same as $cart.find(".row"). Both are fine, but the .find() form reads left to right and is the one most teams prefer.

Narrowing has a second benefit besides speed: it makes code safer. Another widget on the page with its own .row elements cannot be affected by accident.

Start with an id, then go simple

An #id lookup is the fastest selection there is, because the browser keeps ids in a hash table. When you can, anchor your search on an id (or on a cached parent) and look for simple things inside it.

Selectors are matched from right to left by the browser. For #nav ul li a, the engine first collects every a on the page and then checks whether each has the right ancestors. A shorter selector with a more specific right-hand end does less work.

Avoid over-qualified selectors

Over-qualifying means adding information the selector does not need.

Over-qualified Better Why
div#menu #menu ids are unique; the tag adds nothing
ul.nav li.item .nav .item classes are specific enough
div.card div.title span.name .card .name extra links just slow the match and break when markup changes
$("form input") $("form").find("input") or a class split into two cheap steps

The deeper cause is maintenance. A selector that mirrors the exact markup breaks the day someone swaps a div for a section.

Prefer CSS selectors over jQuery extensions

Selectors such as :visible, :first or :eq(2) are jQuery extensions, not CSS. The browser cannot run them natively, so jQuery selects broadly and filters in JavaScript. Select with plain CSS first and refine with a method, as covered in filtering selectors and in the next lesson on filtering methods:

JavaScript
// Slow path: jQuery extension inside the selector string
$(".item:visible");

// Fast path: CSS selector, then a method
$(".item").filter(":visible");

Measure, do not guess

Intuition about performance is often wrong. Use console.time() and console.timeEnd() to compare two versions on your own page, with realistic data. The numbers below depend on your machine, so your results will differ and may even vary from run to run.

Timing three ways to find the same elements

All three find exactly the same 3,000 elements, so you are free to pick the clearest one. When the differences are tiny, choose clarity. The numbers become interesting only when the same lookup runs hundreds of times or the page is very large.

When it actually matters

Most pages never need heavy tuning. Optimize when you see a real symptom: a scroll handler that stutters, a table that takes a visible moment to update, a loop that touches thousands of rows. Open the browser's performance panel, find the hot spot and fix that. The habits in this lesson (cache, narrow, keep selectors simple) cost nothing, so use them by default; anything fancier should be justified by a measurement.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is it better to write const $items = $('.item'); once than to call $('.item') several times?

    Selecting does real work every time: searching the DOM and wrapping the result. A cached variable pays that price once. The elements themselves are not duplicated.
  2. 2. Which line searches only inside the element stored in $cart?

    .find() searches the descendants of every element in the set. .filter() only keeps matching members of the set itself.
  3. 3. What is wrong with the selector div#menu?

    div#menu works but is over-qualified. #menu is shorter, faster and survives a change of tag.
  4. 4. After you cache $rows = $('.row'), more rows are added to the page. What does $rows contain?

    A jQuery object is a snapshot of the elements found at that moment. Re-select, or use event delegation, to deal with later additions.

Summary

  • A selection costs a search plus a new jQuery object; cache anything you use more than once, and name it with a leading $ by convention.
  • Chain calls on one selection instead of selecting again.
  • Search inside a known container with .find() (or the context argument) rather than the whole document.
  • Anchor on an #id, keep selectors short and avoid tag-qualified ids and long chains.
  • Use CSS selectors and refine with methods such as .filter() instead of jQuery-only extensions.
  • Measure with console.time() or performance.now() before and after; most pages do not need more than the basic habits.

Next up: Filtering Methods shows how to narrow an existing selection with .filter(), .not(), .has() and friends.