← Back to jQuery Course | Chapter 15: Performance & Best Practices | Lesson 1 of 5

Caching Selectors

Selector caching means saving a selected jQuery object in a variable and reusing it. This avoids selecting the same element many times.
Syntax
javascript
var $element = $(selector);
$element.action();

What is Selector Caching?

Selector caching means running a jQuery selector once, storing the resulting jQuery object in a variable, and reusing that variable instead of re-running the same selector every time you need that element again. Each time a selector runs, jQuery has to search the DOM again, which adds up if it happens repeatedly.

Example: What is Selector Caching?

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <p id="text">Text</p>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    $("#runBtn").click(function() {
      const $text = $("#text");
      $text.css("color", "red");
      $text.css("font-size", "18px");
    });

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
    });
  </script>
</body>
</html>

Why Cache Selectors?

Caching is especially helpful when the same element or set of elements gets used many times within the same function or event handler, since it avoids repeating an identical, potentially expensive DOM lookup on every use. It also tends to make the code shorter and easier to read.

Example: Why Cache Selectors?

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <button id="btn">Click</button>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    function init() {
      const $btn = $("#btn");
      $btn.on("click", function() {
        $btn.css("background", "yellow");
      });
    }
    init();

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
      init();
    });
  </script>
</body>
</html>

Cache Before Repeated Work

If a loop or a frequently-triggered event handler uses the same selector on every iteration or every call, store the resulting jQuery object in a variable before the loop or handler runs, rather than re-selecting it each time. This keeps repeated work out of code paths that execute often.

Example: Cache Before Repeated Work

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <ul id="list"><li>One</li><li>Two</li></ul>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    $("#runBtn").click(function() {
      $("#output").empty();
      const $items = $("#list li");
      $items.each(function() {
        $(this).css("color", "blue");
      });
    });

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
    });
  </script>
</body>
</html>

Cache Inside Functions

A cached selector is often created once at the top of a function that works with the same element or elements several times within its body, so the selection only happens once no matter how many times that function is called or how it branches internally.

Example: Cache Inside Functions

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    #box { background:steelblue; color:#1a1a1a; padding:10px; border-radius:4px; display:inline-block; margin:10px 0; }
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <div id="box">Box</div>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    $("#runBtn").click(function() {
      function styleBox() {
        const $box = $("#box");
        $box.css("color", "red");
        $box.css("padding", "10px");
      }
      styleBox();
    });

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
    });
  </script>
</body>
</html>

Small Caching Project

Caching is a simple, low-risk optimization — reach for it whenever you notice the exact same selector string appearing more than once in code that runs repeatedly, such as inside an event handler or a loop.

Example: Small Caching Project

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <button id="btn">Click</button>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    function init() {
      const $btn = $("#btn");
      $btn.on("click", function() {
        $btn.text("Clicked!");
      });
    }
    init();

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
      init();
    });
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing $("#text") again and again inside a loop, running the lookup every iteration instead of storing it once: const $text = $("#text");.
  2. Caching a selection before the elements exist, so the variable holds an empty set even after they are added later.
  3. Caching a selector too early, such as $(".item") before items are added, so the stored set does not include elements created later.
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.