Exploring jQuery Selectors, Part 3
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.
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. |
Even (":even") |
Select elements with even-numbered indexes starting with index 0. For example, $('.note:even') selects all even elements whose class value is note. |
First (":first") |
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. |
Odd (":odd") |
Select elements with odd-numbered indexes starting with index 1. For example, $('.note:odd') selects all odd elements whose class value is note. |
Listing 1 presents an HTML document that demonstrates the :animated selector.
Listing 1: Experimenting with the :animated selector.
<html> <head> <title>Filter Selector Demo: ":animated"</title> <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.2.min.js"> </script> </head> <body> <div id="1"> first division </div> <p> <div id="2"> second division </div> <p> <div id="3"> third division </div> <p> <button id="cc">Change Background Color of Animated Div</button> <script type="text/javascript"> $(function() { $("div").css("border-style", "solid"); function animateDiv() { $('div[id="2"]').fadeToggle("slow", animateDiv); } animateDiv(); $("#cc").click(function() { function rndColor() { function rc() { var s = Math.floor(Math.random()*256).toString(16); if (s.length == 1) s = "0"+s; return s; } return "#"+rc()+rc()+rc(); } $("div:animated").css("background-color", rndColor()); }); }); </script> </body> </html>
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).
The anonymous function passed to click() defines function rndColor() to return a randomly generated CSS color string. It then executes $("div:animated").css("background-color", rndColor()); to change the animated <div> element's background color.
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 presents an HTML document that demonstrates the Nth-child(n) selector.
Listing 2: Experimenting with the Nth-child(n) selector.
<html> <head> <title>Filter Selector Demo: Nth Child</title> <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.2.min.js"> </script> </head> <body> <div> The first <span>span element</span> is colored red and the second <span>span element</span> is colored green. </div> <script type="text/javascript"> $(function() { $("div span:nth-child(1)").css("color", "red"); $("div span:nth-child(2)").css("color", "green"); }); </script> </body> </html>
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.
Figure 2 The nested <span> elements are colored red and 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 presents an HTML document that demonstrates :parent and :empty.
Listing 3: Experimenting with the :parent and :empty selectors.
<html> <head> <title>Filter Selector Demo: Parent Versus Empty</title> <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.2.min.js"> </script> </head> <body> <table> <tr> <td>Cell (1, 1)</td> <td></td> </tr> <tr> <td></td> <td>Cell (2, 2)</td> </tr> </table> <script type="text/javascript"> $(function() { $("td:parent").css("border-style", "solid"); $("td:empty").text("was empty").css("border-style", "dotted"); }); </script> </body> </html>
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.
Figure 3 Placing $("td:empty") first eliminates the dotted borders. Why? (Check out my answer in the comments.)
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 presents an HTML document that demonstrates :hidden and :visible.
Listing 4: Experimenting with the :hidden and :visible selectors.
<html> <head> <title>Form Selector Demo: ":hidden" and ":visible"</title> <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.2.min.js"> </script> </head> <body> <form enctype="multipart/form-data" action="" method="POST"> <p> <input type="hidden" name="MAX_FILE_SIZE" value="50000"> Send this file: <input name="chosenfile" type="file"> <input type="submit" value="Send File"> </form> <script type="text/javascript"> $(function() { var numHidFields = $("input:hidden").length; var numVisFields = $("input:visible").length; alert("This form contains "+numHidFields+" hidden field"+ (numHidFields != 1 ? "s": "")+" and "+numVisFields+" visible field"+ (numVisFields != 1 ? "s": "")+"."); }); </script> </body> </html>
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.)