Like this article? We recommend

In the first two parts of this series, you gained an understanding of the heart of the jQuery JavaScript library—selectors. Part 1 introduced you to jQuery's selectors feature and demonstrated its basic and hierarchy selector categories. Part 2 focused on the form and attribute selector categories. Part 3 concludes this series by exploring filter, extension, and custom selectors.

Note

I built and tested this article's code with jQuery 1.7.2 and Mozilla Firefox 12.0. Windows 7 was the underlying platform.

Filter Selectors

jQuery classifies some of its selectors as filters for narrowing the returned selection. Along with the multiple attribute selector discussed in Part 2, which is based on filters, jQuery documents basic, child, content, and visibility filters.

Basic Filters

Basic filters narrow selections to elements that are being animated, or elements based on their position in a matched set. The following table lists the supported basic filters.

Basic Filter

Description

Animated (":animated")

Select all elements that are in the process of animation at the time the selector is run. For example, $("div:animated") selects all <div> elements that are being animated.

Eq (":eq(n)")

Select the element at the specified zero-based index n within the matched set. For example, $('.note:eq(1)') selects the second element whose class value is note.

Select the first matched element. For example, $('.note:first') selects the first element whose class value is note.

Focus (":focus")

Select the element that is currently focused. For example, $('input:focus') selects the <input> element that has focus.

Gt(":gt(n)")

Select all elements at an index greater than the specified zero-based index n within the matched set. For example, $('.note:gt(1)') selects all elements following the second element whose class value is note.

Header (":header")

Select all elements that are headers (<h1>, <h2>, <h3>). For example, $(":header") selects all header elements.

Last (":last")

Select the last matched element. For example, $('.note:last') selects the last element whose class value is note.

Lt (":lt(n)")

Select all elements at an index less than the specified zero-based index n within the matched set. For example, $('.note:lt(3)') selects a maximum of the first three elements whose class value is note.

Not (":not(selector)")

Select all elements that don't match the given selector. For example, $('.note:not(:eq(1))') selects all elements whose class value is note except for the second element.

Listing 1 specifies three <div> elements where the second element is animated. It also specifies a <button> element that, when clicked, changes the background color of the animated <div> via a handler registered in the <script> element.

The <script> element first executes $("div").css("border-style", "solid"); to give each <div> element a solid border. It then defines an animateDiv() function for animating the second <div> element's opacity between opaque and transparent.

The animateDiv() function invokes jQuery's fadeToggle([duration][, easing][, callback]) method, passing "slow" to duration and animateDiv to callback. No argument is passed to easing.

The argument passed to duration identifies the number of milliseconds in which an animation cycle (opaque to transparent, or transparent to opaque) takes place. Although typically a number is passed, you can pass a string such as "slow", which represents 600 milliseconds.

At the end of the cycle, the function passed to callback is invoked. Because animatedDiv is passed as an argument, this function will be invoked to begin a new animation cycle in the opposite direction to the cycle just ended.

The <script> element now executes animatedDiv() to begin the animation. Having done so, it executes $("#cc").click(function(){ /* ... */ }) to register a click event-handler with the <button> element (whose id attribute value is set to cc).

Figure 1 shows the resulting page with a randomly generated background color for the second <div> element after Change Background Color of Animated Div is clicked.

Figure 1 The second <div> element is repeatedly animated from opaque to transparent and back to opaque.

Child Filters

Child filters select elements that are children of their parents based on position or whether they're the sole children. The following table lists the supported child filters.

Child Filter

Description

First Child (":first-child")

Select all elements that are the first child of their parent elements. For example, $("ul li:first-child") returns the first <li> element in each matched <ul> element.

Last Child (":last-child")

Select all elements that are the last child of their parent elements. For example, $("ul li:last-child") returns the last <li> element in each matched <ul> element.

Nth Child (":nth-child(n)")

Select all elements that are the nth-child of their parent elements. For example, $("ul li:nth-child(2)") returns the second <li> element in each matched <ul> element. jQuery's nth-child(n) implementation is strictly derived from the CSS specification, meaning that the value of n is 1-based.

Only Child (":only-child")

Select all elements that are the only child of their parent elements. For example, $("ul li:only-child(2)") returns the <li> element in each matched <ul> element where the <li> element is the only child of the <ul> element.

Listing 2 specifies a single <div> element containing text, along with a pair of nested <span> elements. It also contains a <script> element for selecting and coloring these <span> elements.

Expression $("div span:nth-child(1)") returns a jQuery object containing the first <span> child element of the <div> element, which is subsequently colored red. The $("div span:nth-child(1)") expression chooses the second <span>, which is colored green.

Figure 2 shows the resulting page with the first <span> child element of the <div> element colored red and the second <span> child element colored green.

Content Filters

Content filters select elements based on whether or not they have content. The following table lists the supported content filters.

Content Filter

Description

Contains (":contains(text)")

Select all elements that contain the specified text. The comparison is case sensitive. For example, $(p:contains('jQuery')) selects all <p> elements that contain jQuery directly or in any child elements.

Empty (":empty")

Select all elements that have no children (including text nodes). For example, $(td:empty())selects all <td> elements that have no child elements—not even text nodes.

Has (":has(selector)")

Select elements that contain at least one element matching the specified selector. For example, $(div:has(span)) selects all <div> elements that contain <span> elements directly or in any child elements.

Parent (":parent")

Select all elements that are the parent of another element, including text nodes. For example, $(td:parent()) selects all <td> elements that have child elements or text. This selector is the opposite of :empty.

Listing 3 specifies a <table> element with four table definitions (cells), where two of these cells are empty. The <script> element places borders around all four cells and inserts text into the empty cells.

Figure 3 shows the resulting page: The formerly empty cells contain was empty and are surrounded by dotted borders, whereas the formerly nonempty cells are surrounded by solid borders.

Visibility Filters

Visibility filters select all elements that are hidden or visible. The following table lists the supported visibility filters.

Visibility Filter

Description

Hidden (:hidden)

Select all elements that are hidden. For example, input:hidden selects all hidden <input> elements. An element is considered hidden when its CSS display property is set to none, when it is a form element that includes the type="hidden" attribute, when its width and height are explicitly set to 0, or when an ancestor element is hidden.

Visible (:visible)

Select all elements that are visible. For example, input:visible selects all visible <input> elements. Elements that consume document space (that is, they have a nonzero width or height) are considered visible even when they have been given a CSS visibility: hidden or opacity: 0 property.

Listing 4 specifies a form for uploading a file. This form includes a hidden field for specifying the maximum size of the file to be uploaded. When this page is loaded, it presents a message as shown in Figure 4, identifying the numbers of hidden and visible fields.

Figure 4 Why does the alert dialog appear each time you click Send File? (Check the comments section for my answer.)