Home > Articles > Programming > Java

Exploring jQuery Selectors, Part 3

  • Print
  • + Share This
Developer Jeff Friesen continues his three-part series that introduces jQuery's selectors. Part 3 concludes this series by exploring filter, extension, and custom selectors.
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.

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.)

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020