TExcelTAD
Home › jQuery › jQuery Selectors

jQuery Selectors

Selectors are how you tell jQuery which elements to work with. jQuery accepts any valid CSS selector, plus a few extra jQuery-only ones. If you know CSS, you already know most of them.

Basic selectors

Selector Matches
$("*") Every element
$("p") All <p> elements
$("#intro") The element with id="intro"
$(".note") All elements with class="note"
$("p.note") <p> elements that have class note
$("h1, h2") All <h1> and <h2> elements
$(this) The current element (inside a handler)

Hierarchy selectors

Selector Matches
$("ul li") <li> anywhere inside a <ul> (descendant)
$("ul > li") <li> that are direct children of a <ul>
$("h2 + p") The <p> immediately after an <h2>
$("h2 ~ p") All <p> siblings after an <h2>

Attribute selectors

Selector Matches
$("[href]") Elements that have an href attribute
$("a[target='_blank']") Links whose target equals _blank
$("a[href^='https']") href starts with https
$("a[href$='.pdf']") href ends with .pdf
$("input[name*='mail']") name contains mail

Try the selectors

Type a selector and press Highlight. Matching elements get a yellow background and the count is logged.

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 14px; }
    .hit { background: #fff176; outline: 2px solid #f9a825; }
    #demo { border: 1px dashed #aaa; padding: 6px; }
  </style>
</head>
<body>
  <input id="sel" value="li.fruit" size="22"> <button id="go">Highlight</button>
  <div id="demo">
    <h3 id="title">Shopping</h3>
    <ul>
      <li class="fruit">Apple</li>
      <li class="veg">Carrot</li>
      <li class="fruit sale">Banana</li>
    </ul>
    <p class="note">Prices on <a href="https://example.com/list.pdf">this PDF</a>.</p>
    <p>Open <a href="https://example.com" target="_blank">the shop</a>.</p>
  </div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#go").on("click", function () {
      $("#demo .hit, #demo.hit").removeClass("hit");
      const selector = $("#sel").val();
      try {
        const $found = $("#demo").find(selector);
        $found.addClass("hit");
        console.log(selector, "→", $found.length, "element(s)");
      } catch (err) {
        console.log("Invalid selector:", selector);
      }
    });
  </script>
</body>
</html>

Ideas to try: .fruit.sale, ul > li, a[href$='.pdf'], h3 + ul, li:first, li:odd, p:contains('shop').

jQuery-only selectors

jQuery adds pseudo-selectors that do not exist in CSS. They are handy, but slower than real CSS selectors because the browser cannot evaluate them natively.

Selector Matches
:first / :last The first / last element of the whole matched set
:even / :odd Elements at even / odd 0-based positions
:eq(n), :gt(n), :lt(n) Element at index n / after n / before n
:contains('text') Elements whose text includes text
:visible / :hidden Elements that take up / do not take up space
:input, :checkbox, :checked, :selected Form-related shortcuts
:has(sel) Elements containing at least one sel

Note: :first, :last, :eq(), :even, :odd, :gt() and :lt() are deprecated since jQuery 3.4. Prefer the methods .first(), .last(), .eq(n), .even(), .odd() and .slice() (.even()/.odd() were added in 3.5).

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    table { border-collapse: collapse; }
    td { border: 1px solid #ccc; padding: 4px 12px; }
  </style>
</head>
<body>
  <table id="t">
    <tr><td>Row 0</td><td>Ana</td></tr>
    <tr><td>Row 1</td><td>Ben</td></tr>
    <tr><td>Row 2</td><td>Chloe</td></tr>
    <tr><td>Row 3</td><td>Dan</td></tr>
    <tr><td>Row 4</td><td>Eve</td></tr>
  </table>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const $rows = $("#t tr");
    $rows.even().css("background", "#eef5fb");   // rows 0, 2, 4 (method form)
    $rows.first().css("font-weight", "bold");
    $rows.eq(3).css("color", "crimson");
    $("#t td:contains('Chloe')").css("background", "#fff176");

    console.log("rows:", $rows.length);
    console.log("visible rows:", $rows.filter(":visible").length);
    console.log("3rd name:", $rows.eq(2).find("td").last().text());
  </script>
</body>
</html>

Performance tips

  • IDs are fastest: $("#menu") maps to getElementById.
  • Narrow the search: $("#menu").find("a") searches only inside #menu.
  • Cache results: store const $items = $(".item") instead of selecting the same thing repeatedly inside a loop.
  • Escape special characters in IDs: an element with id="a.b" needs $("#a\\.b") or $("#" + $.escapeSelector("a.b")).

Test yourself

Which selector matches only <li> elements that are direct children of a <ul>?

  1. $("ul li")
  2. $("ul > li")
  3. $("ul + li")
  4. $("ul ~ li")

What does $("a[href$='.pdf']") select?

  1. Links whose href starts with .pdf
  2. Links whose href contains .pdf anywhere
  3. Links whose href ends with .pdf
  4. Links with a pdf class

Since jQuery 3.4, what should you use instead of the :eq(2) selector?

  1. .eq(2)
  2. .index(2)
  3. :nth(2)
  4. .get(2).css()