jQuery · Basics

Selectors

Everything in jQuery starts by selecting elements. If you know CSS selectors, you already know most of jQuery’s — plus a few handy extras.

Beginner 5 min Lesson 3 of 22 Runnable examplesExamples use jQuery 3.x.
Before you start:Installing jQuery
0/22 in jQuery
On this page · 5 min · Beginner

Learning objectives#

  • Select by id, class, tag and attribute
  • Use descendant, child and pseudo selectors
  • Filter and count matched elements
  • Tell a jQuery object from a DOM element

Explanation#

$("#id"), $(".class") and $("tag") work like CSS. Combine them: $("ul.menu > li"), $("input[type=email]").

jQuery adds filters: :first, :last, :even, :odd, :visible, :checked, :contains("text"). Methods like .first(), .eq(2) and .filter(".x") do the same and are faster.

$() always returns a jQuery object — even when nothing matches. Check .length to know how many elements were found.

A jQuery object is a list of DOM elements with jQuery methods. $(".x")[0] or .get(0) gives the raw DOM element; $(domElement) wraps one back.

Store selections you reuse in variables (by convention starting with $): const $rows = $("#orders tr");.

Syntax#

JavaScript Illustrative
$('#cart')               // id
$('.item')               // class
$('li:first')            // first li
$('input[type=email]')   // attribute
$('#menu > li.active')   // child + class

Code example: Selecting and counting#

HTMLSelecting and counting Runnable
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<ul id="menu" style="font-family:sans-serif">
  <li>Home</li><li class="active">Shop</li><li>Blog</li><li>Contact</li>
</ul>
<input type="email" placeholder="email"> <input type="text" placeholder="name">
<script>
  $(function () {
    console.log('All items:', $('#menu li').length);
    console.log('Active:', $('#menu li.active').text());
    console.log('Third:', $('#menu li').eq(2).text());
    console.log('Odd rows:', $('#menu li:odd').length);
    console.log('Email inputs:', $('input[type=email]').length);
    console.log('Missing:', $('.does-not-exist').length);
    $('#menu li:first').css('font-weight', 'bold');
  });
</script>
Expected output
All items: 4
Active: Shop
Third: Blog
Odd rows: 2
Email inputs: 1
Missing: 0
(“Home” is shown in bold.)
Opens this example in the full playground

Step-by-step explanation#

  1. $("#menu li") finds all four list items inside #menu.
  2. .text() on the active item returns “Shop”.
  3. .eq(2) picks the third match (indexes start at 0).
  4. :odd matches indexes 1 and 3 — two items.
  5. A selector that matches nothing returns an empty jQuery object with length 0, not null.

Real-world use case#

An admin table highlights overdue invoices with $("#invoices tr[data-status=overdue]").addClass("danger") — one line, every matching row.

Common mistakes#

Checking if ($(".x")) for existence

A jQuery object is always truthy. Use if ($(".x").length).

Forgetting # or .

$("cart") looks for a <cart> tag. Use $("#cart") or $(".cart").

Calling jQuery methods on DOM elements

$("li")[0].addClass("x") fails because [0] is a raw element. Use .eq(0) instead.

Best practices#

  • Prefer ids and classes for speed
  • Cache repeated selections in $variables
  • Scope searches: $container.find(".x")
  • Use .length to test for matches

Remember this#

jQuery selectors = CSS selectors (+ extras).

Nothing found? Still an object — check .length.

[0] = DOM element. .eq(0) = jQuery object.

Practice exercise#

Your task: Given a table with rows that have data-status="paid" or "due", log how many are due and colour them red.

Need a hint?
Use an attribute selector: $("tr[data-status=due]").
Show solution
HTML Runnable
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<table>
  <tr data-status="paid"><td>INV-1</td></tr>
  <tr data-status="due"><td>INV-2</td></tr>
  <tr data-status="due"><td>INV-3</td></tr>
</table>
<script>
  $(function () {
    const $due = $('tr[data-status=due]');
    console.log('Due:', $due.length);   // Due: 2
    $due.css('color', 'red');
  });
</script>
Opens this example in the full playground

Mini quiz#

Selectors quizMultiple choice Question 1 of 3

Which selector finds the element with id "cart"?

Score so far: 0/0

Want more? Practise all jQuery MCQs · jQuery interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.