Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 56 ยท Selecting Elements

Filtering Selectors and jQuery Extensions

Learn jQuery's filter selectors such as :first, :even, :not, :has, :contains, :visible and :checked, their costs, and why .filter() is often the better choice.

Standard CSS selectors describe elements by their tag, class, attributes and position in the tree. They cannot say things like "the third item in this selection", "rows with an even index" or "elements that are currently visible". jQuery fills those gaps with its own extension selectors, written as pseudo-classes after a colon.

In this lesson you will learn the extensions you are most likely to meet in existing code, what each one really means, and why modern jQuery style prefers to move them out of the selector string and into a .filter() call.

Position filters

These select by a position in the set of elements matched so far (not by position inside the parent):

Selector Meaning
:first the first element of the set
:last the last element of the set
:eq(n) the element at zero-based index n (negative counts from the end)
:even elements at index 0, 2, 4, ...
:odd elements at index 1, 3, 5, ...
:gt(n) / :lt(n) elements with an index greater / less than n

Pay attention to the word zero-based. :even selects the first, third and fifth elements, because their indexes are 0, 2 and 4. People reading a table by eye number its rows from 1, so :even often looks like the "odd" rows. Use whichever you need, and verify visually.

Position filters on a table

:first and :last look like the CSS pseudo-classes :first-child and :last-child, but they are different. li:first returns only one element for the whole selection, while li:first-child returns every <li> that is the first child of its parent, which can be many.

Content and relationship filters

Several extensions look inside the elements instead of at their position:

Selector Meaning
:not(sel) elements that do not match sel
:has(sel) elements that contain a descendant matching sel
:contains(text) elements whose text includes text (case-sensitive)
:empty elements with no children and no text
:parent elements that have at least one child or text node

:not() and :has() are now part of the CSS standard as well, so many browsers accept them natively and querySelectorAll can handle them. :contains() is purely a jQuery feature, and the text you pass is matched anywhere in the element's text, including inside nested elements. It is case-sensitive: :contains("Sale") will not match "sale".

JavaScript
$("li:not(.done)")            // list items that are not done
$("div:has(img)")             // divs that contain an image somewhere inside
$("p:contains('Warning')")    // paragraphs mentioning Warning

State and form filters

Another family reports on the current state of an element or its type:

Selector Meaning
:visible elements that take up space in the layout
:hidden elements that do not, plus <input type="hidden">
:checked checked checkboxes and radio buttons, and selected options
:selected selected <option> elements
:disabled / :enabled form controls in that state
:input input, textarea, select and button elements
:header h1 to h6
:text, :checkbox, :radio ... form controls by type (deprecated)

:visible and :hidden deserve a careful note. jQuery calls an element visible when it has a layout box with a width or height greater than zero. That means display: none makes an element hidden, an element with zero size is hidden, but visibility: hidden and opacity: 0 elements still occupy space and therefore count as visible. Because these filters ask the browser to compute layout, they are among the more expensive ones.

State filters on a small form

Look at the two paragraphs: #f p:hidden finds only the one with display:none, while #f p:visible finds the ghost paragraph, because it still occupies space. Note also that :input counts the select and the button as well as the text, checkbox and hidden fields.

Form-type selectors in detail

Each form-type selector is a shortcut for an attribute test, and understanding the shortcut tells you what it really matches.

Shortcut Plain CSS equivalent Notes
:radio input[type="radio"] radio buttons only
:password input[type="password"] password fields only
:text input[type="text"] (and inputs with no type) in older jQuery also matched type-less inputs
:button button, input[type="button"] every <button> element (any type) plus input[type=button]; not input[type=submit]
:submit button[type="submit"], input[type="submit"] <button> with no type counts as submit

Because these are jQuery extensions, jQuery cannot hand them to the browser's fast selector engine. The recommended way is to use the CSS form first and add a .filter() only if you need it: $("input[type=radio][name=plan]") picks the radio group named plan, and $("form :radio") is the shortcut for every radio button in a form.

Form-type selectors

Notice that :button finds two elements (the <button> and the input[type=button]) and leaves the input[type=submit] out; a <button type="submit"> would be counted by both :button and :submit. :header is similar: it matches h1 to h6 in one go, which $("h1, h2, h3, h4, h5, h6") writes out longhand.

Structural and positional selectors that are plain CSS

The deprecated extensions above have standard CSS replacements. Because they are real CSS, jQuery hands them to querySelectorAll and they stay fast. Keep this list close; it is the one you want in new code.

Selector Matches
:first-child, :last-child an element that is the first or last child of its parent, whatever its tag
:only-child an element with no siblings
:nth-child(n), :nth-last-child(n) the n-th child counted from the start or the end; n can be a number, odd, even, or a formula such as 3n+1
:first-of-type, :last-of-type the first or last element of its tag among its siblings
:nth-of-type(n), :nth-last-of-type(n) the n-th element of its tag, counting from the start or the end
:only-of-type an element that is the only one of its tag among its siblings
:root the document element, <html>
:lang(en) elements whose language, set by lang on the element or an ancestor, matches en
:empty elements with no children and no text
:not(selector) elements that do not match the selector

The difference between -child and -of-type is a classic trap. In the example below, p:first-child finds nothing, because the first child of the div is the h2, but p:first-of-type finds One. Counting from the end works the same way: p:nth-last-of-type(2) is the second-to-last paragraph, Two.

Two more names appear in old code, and both are jQuery-only: :header (any h1 to h6, listed above) and :animated, which matches elements currently being animated:

JavaScript
$(":animated").length;                 // how many elements are animating right now
$("div:not(:animated)").fadeToggle();  // do not start a second animation on a busy element

:animated is useful as a guard in click handlers, although .stop(true, true) before starting the next animation (see Animation Queue) usually gives a better result. For :header, write the explicit list h1, h2, h3, h4, h5, h6 if you want a CSS selector.

Child versus of-type, :root and :lang

The cost of non-CSS selectors

Recall from the Basic Selectors lesson that jQuery can hand valid CSS to the browser's very fast querySelectorAll. A selector with a jQuery-only extension such as :visible, :eq(), :contains() or :first is not valid CSS. The browser rejects it, and jQuery falls back to its own selector engine, which has to check candidate elements one by one in JavaScript.

On a small page you will never notice. On a page with thousands of elements, or in code that runs on every mouse move, the difference adds up.

There is a second reason to be careful. Since jQuery 3.4, the positional extensions (:first, :last, :eq, :even, :odd, :gt, :lt) are deprecated. They still work, but they are not expected to be part of future selector engines, and they warn about being deprecated if you use the migration plugin. Write new code without them.

Prefer .filter() on a CSS selection

The recommended approach is to split the work in two. First let the browser do the fast part, then narrow the result with a jQuery method:

JavaScript
// Old style: one slow, extension-based selector
$("#t tr:even").addClass("zebra");

// Preferred: fast CSS selection, then filter
$("#t tr").filter(":even").addClass("zebra");
$("#t tr").first().addClass("first");
$("#t tr").last().addClass("last");
$("#t tr").eq(2).addClass("third");

For positions, the methods .first(), .last() and .eq(n) do exactly what :first, :last and :eq(n) do. For :even and :odd there is a pure-CSS choice, :nth-child(odd), which works from the standard parent-relative positions, and for custom logic you can pass a function to .filter(). The Filtering Methods lesson goes through all of these.

For visibility, :visible and :hidden have no CSS equivalent, so they remain in use. If you want to test one element, .is(":visible") is a clean way, and doing it on an already narrow selection keeps the cost low. Where you can, check a class that your own code controls (.hasClass("open")) instead of asking the browser about layout.

Same result, faster pattern

All three produce the same list. The function form is the most flexible because it can use any logic you like, not only the position.

Two kinds of selector

Plain CSS Handled natively by the browser. Fast.
jQuery extensions :first, :eq, :even, :contains, :visible.
Fallback Extensions run in slower JavaScript.
Best habit CSS first, then .filter() or .first().

Positional extensions are deprecated since jQuery 3.4.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. $("tr:even") selects rows at which indexes?

    jQuery positions are zero-based, so :even picks the first, third, fifth rows, which have indexes 0, 2, 4.
  2. 2. What is the difference between li:first and li:first-child?

    :first is a jQuery position filter on the matched set. :first-child is standard CSS and is relative to each parent.
  3. 3. An element has visibility:hidden. What does $(el).is(":visible") return?

    jQuery's :visible means the element has layout size. Elements with visibility:hidden or opacity:0 still occupy space.
  4. 4. Why is $("li").filter(":even") usually better than $("li:even")?

    A selector containing an extension cannot use querySelectorAll. Selecting with CSS first and filtering afterwards keeps the fast path.

Summary

  • jQuery adds extension selectors such as :first, :last, :eq(), :even, :odd, :contains(), :visible, :hidden, :checked, :selected, :input and :header.
  • Position filters are zero-based and operate on the matched set; :first is not the same as CSS :first-child.
  • :not() and :has() are standard CSS now; :contains() is case-sensitive.
  • :visible means "has layout size"; visibility:hidden and opacity:0 elements still count as visible.
  • Extension selectors bypass querySelectorAll, and the positional ones are deprecated since jQuery 3.4, so prefer a CSS selector followed by .filter(), .first(), .last() or .eq().

Next, let's look at selector performance and caching.