CHAPTER 4

image

jQuery Selectors Filtering and Expansion

This chapter covers jQuery selectors filtering (narrowing) and expansion. jQuery selector filtering is used to narrow down the set of selected elements and the expansion method is used to add more elements to the set of selected elements. Programming logic can be used to include, exclude, or replace selected elements in the set. Once you have the desired set of elements, you can access and manipulate their attributes values, properties, and style.

This chapter includes recipes that show you how to fine-tune sets of selected elements using filtering and expansion in order to:

  • Access their style, properties, and attributes
  • Manipulate their style, properties, and attributes

4-1. Narrowing the Set of Selected Elements by Using Selector/jQuery Object Filter

Problem

You want to narrow down the set of selected elements by selecting only specific elements.

Solution

The following jQuery selector syntax selects the HTML elements from the set of already selected HTML elements, which match the specified selector.

$(selector).filter(filterSelector)

Listing 4-1 provides an example to demonstrate the use of the filter() method to select specific HTML elements from the set of selected elements.

Listing 4-1. Using filter() to select specific elements

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
      border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .newRecord {
         background-color: lightyellow;
      }
      .listDepartments {
         width: 200px;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $("tr").filter(".newRecord").css("background-color", "lightblue");
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
      <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr class="newRecord">
         <td>John Smith</td><td>Technology</td><td>$76,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
      <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <strong>Departments:</strong>
      <ul class="listDepartments">
         <li>Marketing</li>
         <li>Sales</li>
         <li class="newRecord">Technology</li>
         <li>Customer Support</li>
     </ul><br>
      <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags and the departments’ names are listed using the <ul> and <li> HTML tags. In both lists, there is one record with the class newRecord. If you want to select newRecord from the table only to perform an action on it, you first select all the records using $("tr") and then use filter(".newRecord").

When the user clicks the Test It button, the following code is executed:

$("tr").filter(".newRecord").css("background-color", "lightblue");

$("tr") selects all HTML elements with tag name "tr" and returns the jQuery object. .filter(".newRecord") selects the HTML element with the class name newRecord from the selected HTML elements array in the returned jQuery object and returns another jQuery object. Refer to Recipe 3-2 for an explanation of the css() method.

When you press the Test It button, the button’s click event handler changes the background color of the selected element to light blue. Figure 4-1 displays the effect of clicking the Test It button.

9781430264330_Fig04-01.jpg

Figure 4-1. Record with newRecord class with light blue background

There are two other ways to filter elements:

  1. Use the filter() method with the argument: selector:
    $("tr").filter(".newRecord");
  2. Use the filter() method with the argument: jQuery object:
    var newRecords = $(".newRecord");;
    $("tr").filter(newRecords);

4-2. Narrowing the Set of Selected Elements by Using the Filter Function

Problem

You want to narrow down the set of selected elements by selecting specific elements based on the return value of a function.

Solution

The following jQuery selector syntax selects HTML elements from the set of already selected HTML elements, from which the filter function returns true.

$(selector).filter( function() { ... });

Listing 4-2 demonstrates the use of the filter() method with the argument as a function to select specific HTML elements from the set of selected elements. The function iterates over all the elements in the set of selected elements and if it returns true, the current element is included in the resultant jQuery object.

Listing 4-2. Using filter(function()) to select specific elements

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $("tr").filter(function() {
                                         return ($(this).children().eq(1).text() == "Technology");
                              }).css("background-color", "lightblue");
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr>
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags and the departments’ names are listed using the <ul> and <li> HTML tags. In both lists, there is one record with the class newRecord. If you want to select newRecord from the table only to perform an action on it, you first select all the records using $("tr") and then use filter(".newRecord").

When the user clicks the Test It button, the following code is executed:

$("tr").filter(function() {
   return ($(this).children().eq(1).text() == "Technology");
   }). css("background-color", "lightblue");

$("tr") selects all the HTML elements with tag name "tr" and returns the jQuery object. .filter(function()) iterates over each element of the selected HTML elements in the returned jQuery object. If the function returns true for the current element, that element is included in resultant jQuery object. At the end of the iteration, the resultant jQuery object is returned. In this case, $(this) is the current element, so $(this).children() returns all the children (i.e., TD elements), $(this).children().eq(1) returns the second TD element, and $(this).children().eq(1).text() returns the text content of the second TD element, which is the department name. This function returns true if the department name is "Technology". Refer to Recipe 3-2 for information on the css() method. The children() method is discussed in the next chapter.

When you press the Test It button, the button’s click event handler changes the background color of the selected element to light blue. Figure 4-2 displays the effect of clicking the Test It button.

9781430264330_Fig04-02.jpg

Figure 4-2. Records from the Technology department have a light blue background

4-3. Narrowing the Set of Selected Elements by Checking Their Descendant Nodes’ Attributes

Problem

You want to narrow down the set of selected elements by selecting only those elements that have descendants that match the specified selector.

Solution

The following jQuery syntax selects only those HTML elements from the set of already selected HTML elements that have descendants matching the specified selector.

$(selector).has(descendantSelector)

Listing 4-3 demonstrates the use of the has() method to select specific HTML elements when their descendant matches the specified selector.

Listing 4-3. Using has() to select specific elements

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      .tableWithNewRecord {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .listDepartments {
         width: 200px;
      }
      .newRecord {
         background-color: lightyellow;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $("table").has(".newRecord").addClass("tableWithNewRecord");
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr class="newRecord">
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br><br>
   <strong>Departments:</strong>
   <table id="listDepartments">
      <tr class="tblHdr">
         <td>Department Code</td><td>Department Name</td></tr>
      <tr><td>D01</td><td>Marketing</td></tr>
      <tr><td>D02</td><td>Sales</td></tr>
      <tr><td>D03</td><td>Technology</td></tr>
      <tr><td>D04</td><td>Customer Support</td></tr>
   </table><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, salary, and the departments names—are listed in tabular form using the <table>, <tr>, and <td> HTML tags. In the employee list, there is one record with the class newRecord. If you want to select a table that has decendent(s) (<TR> or <TD>) with the class name newRecord, you first select all the table elements using $("table") and then use the descendant filter as has(".newRecord").

When the user clicks Test It button, the following code is executed:

$("table").has(".newRecord").addClass("tableWithNewRecord");

$("table") selects all the HTML elements with tag name "table" and returns a jQuery object. .has(".newRecord") selects HTML elements with a descendent’s class name newRecord from the selected HTML elements and returns another jQuery object. The addClass("tableWithNewRecord") method is executed on the selected HTML element in the returned jQuery object. addClass("tableWithNewRecord") adds the CSS class to the selected elements.

When you press the Test It button, the button’s click event handler adds a new class (tableWithNewRecord) to the employee table. Figure 4-3 displays the effect of clicking the Test It button.

9781430264330_Fig04-03.jpg

Figure 4-3. Table with descendent(s) having newRecord class

4-4. Narrowing the Set of Selected Elements by Excluding Elements Using Selectors

Problem

You want to narrow down the set of selected elements by excluding some elements specified by the exclusion selector.

Solution

The following jQuery selector syntax selects the HTML elements from the set of already selected HTML elements that are not matching specified selector.

$(selector).not(exclusionSelector)

The not() method’s functionality is the reverse of the filter() functionality, where filter allows elements to go through based on the specified selector, not blocks certain elements that match the specified selector. Listing 4-4 provides an example to demonstrate the use of the not() method to exclude specific HTML elements from the set of selected elements.

Listing 4-4. Using not() to exclude specific elements

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .newRecord {
         background-color: lightyellow;
      }
      .listDepartments {
         width: 200px;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $("tr").not(".newRecord").css("background-color", "lightblue");
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr class="newRecord">
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <strong>Departments:</strong>
   <ul class="listDepartments">
      <li>Marketing</li>
      <li>Sales</li>
      <li class="newRecord">Technology</li>
      <li>Customer Support</li>
   </ul><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags and the departments’ names are listed using the <ul> and <li> HTML tags. In both lists, there is one record with the class newRecord. If you want to select non-newRecord records from the table only to perform an action on them, you first select all the records using $("tr") and then use filter(".newRecord").

When the user clicks the Test It button, the following code is executed:

$("tr").not(".newRecord").css("background-color", "lightblue");

$("tr") selects all the HTML elements with tag name "tr" and returns a jQuery object. .not(".newRecord") selects all the HTML elements except the element with the class name of "newRecord" from the selected HTML elements and returns another jQuery object. Refer to Recipe 3-2 for an explanation of the css() method.

When you press the Test It button, the button’s click event handler changes the background color of the selected elements to light blue. Figure 4-4 displays the effect of clicking the Test It button.

9781430264330_Fig04-04.jpg

Figure 4-4. All records except the record with the newRecord class are highlighted with a light blue background

Here are two other ways to filter elements using the not() method:

  1. Using the not() method with the argument: selector:
    $("tr").not(".newRecord");
  2. Using the not() method with the argument: jQuery object:
    var newRecords = $(".newRecord");
    $("tr").not(newRecords);

4-5. Narrowing Down the Set of Selected Elements by Excluding Elements Using a Function

Problem

You want to narrow down the set of selected elements by excluding some elements identified by a function.

Solution

The following jQuery selector syntax selects the HTML elements from the set of already selected HTML elements that do not match elements for which a function has returned true.

$(selector).not(function () {...})

Listing 4-5 provides an example to demonstrate the use of the not() method, with a function as an argument, to exclude specific HTML elements from the set of selected elements.

Listing 4-5. Using not(function()) to exclude specific elements

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .listDepartments {
         width: 200px;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $("tr:gt(0)").not(function(index) {
                               return ($(this).children().eq(1).text() == "Technology");
                             }).css("background-color", "lightblue");
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr>
         <td>John Smith</td><td>Technology</td><td>$76,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags. If you want to select all the records except for the header record and records with department name as "Technology" and perform an action on the selected items, you first select all records except for header record using $("tr:gt(0)") and then use not(function() { ... }). The function will return true if current record has the department name of "Technology".

When the user clicks the Test It button, the following code is executed:

$("tr:gt(0)").not(function(index) {
   return ($(this).children().eq(1).text() == "Technology");
}).css("background-color", "lightblue");

$("tr:gt(0)") selects all the HTML elements with tag name "tr" with index number > 0 and returns a jQuery object. The .not(function()) iterates over each element of the selected HTML elements in the returned jQuery object. If the function returns true for the current element, that element is excluded in resultant jQuery object and after the end of the iteration, the resultant jQuery object is returned. In this case, $(this) is the current element, $(this).children() returns all the children (i.e., TD elements), $(this).children().eq(1) returns the second TD element, and $(this).children().eq(1).text() returns the text content of the second TD element, which is the department name. This function returns true if the department name is "Technology" and hence is excluded. Refer to Recipe 3-2 for an explanation of the css() method. The children() method is discussed in the next chapter.

When you press the Test It button, the button’s click event handler changes the background color of all the selected elements to light blue. Figure 4-5 displays the effect of clicking the Test It button.

9781430264330_Fig04-05.jpg

Figure 4-5. Records are highlighted if the department name is not Technology

4-6. Narrowing Down the Set of Selected Elements by Selecting a Range of Elements by Index

Problem

You want to narrow down the set of selected elements by selecting elements within a range of indexes.

Solution

The following jQuery selector syntax selects HTML elements from the set of already selected HTML elements with an index number within a specified index range.

$(selector).slice(startIndexNumber, endIndexNumber)

HTML elements are selected with an index number greater than or equal to startIndexNumber and less than endIndexNumber. endIndexNumber is optional, if it is not specified all the elements starting with startIndexNumber until the end of the array will be selected. Listing 4-6 provides an example to demonstrate the use of the slice() method to select a range of HTML elements based on their index number. The index number is zero-based.

Listing 4-6. Using slice() to select a range of elements

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .listDepartments {
         width: 200px;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $("tr").slice(2,4).css("background-color", "lightblue");
                                          $("li").slice(1).css("background-color", "lightblue");
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$80,000</td>
      </tr>
      <tr>
         <td>John Smith</td><td>Technology</td><td>$76,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <strong>Departments:</strong>
   <ul class="listDepartments">
      <li>Marketing</li>
      <li>Sales</li>
      <li>Technology</li>
      <li>Customer Support</li>
   </ul><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags and the departments’ names are listed using the <ul> and <li> HTML tags. In both lists, there is one record with the class newRecord. If you want to select newRecord from the table only to perform an action on it, you first select all records using $("tr") and then use filter(".newRecord").

When the user clicks the Test It button, the following code is executed:

$("tr").slice(2,4).css("background-color", "lightblue");
$("li").slice(1).css("background-color", "lightblue");

$("tr") selects all HTML elements with tag name “tr” and returns the jQuery object. .slice(2, 4) selects HTML elements with index numbers 2 and 3 from the selected HTML elements and returns another jQuery object. The css() method is executed on the selected HTML element in the returned jQuery object. css("background-color", "lightblue") changes the background color of the selected element to light blue.

$("li") selects all the HTML elements with tag name "li" and returns a jQuery object. .slice(1) selects HTML elements starting with index number 1 until the end from the selected HTML elements and returns another jQuery object. Refer to Recipe 3-2 for an explanation of the css() method.

When you press the Test It button, the button’s click event handler changes the background color of the selected elements to light blue. Figure 4-6 displays the effect of clicking the Test It button.

9781430264330_Fig04-06.jpg

Figure 4-6. Selecting records using the slice() method

4-7. Adding More Elements to the Set of Selected Elements

Problem

You want to add more HTML elements to a set of selected elements.

Solution

The following jQuery syntax adds more elements to the set of selected elements:

$(selector1).add(selector2)

Listing 4-7 provides an example to demonstrate the use of the add() method.

Listing 4-7. Adding more elements to already selected ones

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .listDepartments {
         width: 200px;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $("tr:gt(0)").add("li").css("background-color", "lightblue");
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr>
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <strong>Departments:</strong>
   <ul class="listDepartments">
      <li>Marketing</li>
      <li>Sales</li>
      <li>Technology</li>
      <li>Customer Support</li>
   </ul><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags and the departments list is displayed using the <ul> and <li> tags. If you want to select table records except for the header record and then add the departments list, begin by selecting the table records using $("tr:gt(0) ") and then use the add("li") method to add elements to previously selected ones.

When the user clicks the Test It button, the following code is executed:

$("tr:gt(0)").add("li").css("background-color", "lightblue");

$("tr:gt(0)") selects all the HTML elements with the tag name "tr" whose index is greater than 0 and returns a jQuery object. .add("li") selects HTML elements with the tag name "li" and adds them to the previously selected records. It returns a resultant jQuery object with the combined set of elements. Refer to Recipe 3-2 for an explanation of the css() method.

When you press the Test It button, the button’s click event handler changes the background color of the selected elements to light blue. Figure 4-7 displays the effect of clicking the Test It button.

9781430264330_Fig04-07.jpg

Figure 4-7. Selected elements with a light blue background

Here are three additional ways to add elements:

  1. Using the add() method with the argument: selector:
    $("tr:gt(0)").add("li");
  2. Using the add() method with the argument: HTMLElements:
    var liElements = document.getElementsByTagName("li");
    $("tr:gt(0)").add(liElements);
  3. Using the add() method with the argument: jQuery object:
    var jqObj = $("li");
    $("tr:gt(0)").add(jqObj);

4-8. Checking if Common HTML Element(S) Exist in Two Sets of Selected HTML Elements

Problem

You want to perform an action on elements from a set of selected HTML elements based on the existence of at least one element in another set of selected HTML elements.

Solution

The following jQuery syntax determines if element(s) from one set of HTML elements exist in another set.

$(selector1).is(selector2)

This method returns a Boolean. If at least one element from selector1 matches elements from selector2, it returns true; otherwise, false is returned. Listing 4-8 demonstrates the use of the is() method to check elements in two sets.

Listing 4-8. Using is() to check elements from two sets

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      .tableWithNewRecord {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .listDepartments {
         width: 200px;
      }
      .newRecord {
         background-color: lightyellow;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            if ($("tr").is(".newRecord")) {
              $("#message").prop("innerHTML", "<strong>There is a new record in the table.</strong>");
           }
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr class="newRecord">
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br><br><br>
   <input id="btnTestIt" type="button" value="Test It"><br><br>
   <div id="message"></div>
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags. If you want to check if any of the "tr" elements have a "newRecord" class, you first select all the records using $("tr") and then use is(".newRecord") to check the condition.

When the Test It button is clicked, the following code is executed:

if ($("tr").is(".newRecord")) {
   $("#message").prop("innerHTML", "<strong>There is a new record in the table.</strong>");
}

$("tr") selects all the HTML elements with the tag name "tr" and returns a jQuery object. .is(".newRecord") checks if any of the HTML elements exist in the set of elements with class name newRecord. In this case, true is returned. $("#message").prop("innerHTML", "<strong>There is a new record in the table.</strong>") gets the <div> with id #message and sets its innerHTML property with the message.

When you press the Test It button, the button’s click event handler displays the message. Figure 4-8 displays the message when the Test It button is clicked.

9781430264330_Fig04-08.jpg

Figure 4-8. Message displayed when the is() method returns true

4-9. Iterating Over Each HTML Element in the jQuery Object to Perform an Action

Problem

You want to perform a different action on each element from a group of HTML elements.

Solution

So far this chapter has discussed how HTML elements can be selected using various basic jQuery selectors and selector extensions and has performed the same action on all of the selected elements. This section covers how different actions can be performed on each of the selected elements based on some logic.

The following jQuery syntax selects each element individually from the set of selected HTML elements.

$("selector").each(function (currentIndexNumber, currentElement) {
   // Code segment to process each element
});

These are the arguments of the inline function():

  • currentElement is the HTML element that’s being processed in this iteration. It is from the array of HTML elements in the jQuery object, which is returned by $("selector").
  • currentIndexNumber is the index number of the current HTML element being processed.

Inside the function, the current element can be accessed using $(this) or $(currentElement). Listing 4-9 demonstrates the use of the each() method, which iterates over each element from the set of selected elements.

Listing 4-9. Iterate over each element in the set of selected elements

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $("tr").each(function (index, htmlElement){
               var bgColor = "";
               if (index == 0) {
                  bgColor = "lightgray";
               } else if (index % 2 == 0) {
                  bgColor = "lightyellow";
               } else {
                  bgColor = "lightblue";
               }
               $(this).css("background-color", bgColor);
            });
         });
      });
   </script>
</head>
<body>
   <table id="tblEmployee">
      <tr>
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr>
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags. Other than the first record (the header record), all the other records (<tr>) use the row CSS class. If you want to select even numbered and odd numbered rows, excluding the header record, you first select all the records using the $(".row") selector and then use the :even and :odd extensions to select the even and odd numbered elements from these matched records.

When the user clicks the Test It button, the following code is executed:

$("tr").each(function (index, htmlElement){
   var bgColor = "";
   if (index == 0) {
      bgColor = "lightgray";
   } else if (index % 2 == 0) {
      bgColor = "lightyellow";
   } else {
      bgColor = "lightblue";
   }
   $(this).css("background-color", bgColor);
   });

$("tr") selects all the HTML elements with the tag name "tr" and returns a jQuery object. .each() iterates through each element in the set of selected HTML elements in the returned jQuery object. The argument of the each() method is an inline function() that has access to the current HTML element being processed and its index number. Based on the index number, code logic decides the value of background color. If it is the first element (index: 0), i.e. header, the background color variable is set as light gray. If the index number is an even number, the background color is set as light yellow. Otherwise, the background color is set to light blue. $(this) is the current HTML element being processed. css("background-color", bgcolor) changes the background color of the currently selected element to the value of bgcolor.

When you press the Test It button, the button’s click event handler changes the background color of selected elements. Figure 4-9 displays the effect of clicking the Test It button.

9781430264330_Fig04-09.jpg

Figure 4-9. Change in background color when Test It button is clicked

4-10. Reverting to the Most Recent Expansion or Narrowing a Set of Selected Elements

Problem

You want to revert (undo) the effect of an expansion or narrow a set of selected elements.

Solution

The following examples of jQuery syntax are used to undo the most recent change and revert to a set of selected elements.

$(selector).add(additonalSelector).manipulationMethod().end()
$(selector).filter(filterSelector).manipulationMethod().end()

Listing 4-10 demonstrates the use of the end() method to revert to the effect of the add() method.

Listing 4-10. Using end() method to revert to the effect of add()

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .listDepartments {
         width: 200px;
      }
   </style>
  <script>
    $(function(){
      $("#btnTestIt").click(function () {
        $("tr:gt(0)").add("li").css("background-color", "lightblue").end().css("text-decoration", "underline");
      });
    });
  </script>
</head>
<body>
   <strong>Employees:</strong>
   <table id="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr>
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <strong>Departments:</strong>
   <ul class="listDepartments">
      <li>Marketing</li>
      <li>Sales</li>
      <li>Technology</li>
      <li>Customer Support</li>
   </ul><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags. When the Test It button is clicked, the following code is executed:

$("tr:gt(0)").add("li").css("background-color",
  "lightblue").end().css("text-decoration", "underline");

$("tr:gt(0)") selects all the HTML elements with the tag name "tr", where the index number is greater than 0 and returns the jQuery object. All the records from the table are selected except for the first one.

.add("li") adds all the HTML elements with the tag name "li" to the previous set of selected records.

css("background-color", "lightblue") changes the background color of the selected elements to light blue.

end() reverts to the most recent expansion or narrowing of elements. In this case, the addition of HTML elements with the tag name "li" is reverted.

css("text-decoration", "underline") changes the text decoration of the current set of elements to underline.

When you press the Test It button, the button’s click event handler changes the background color of all the "tr" elements (except for the header) and "li" elements to light blue and underlines the "tr" elements only. Figure 4-10 displays the change in the background color and text decoration.

9781430264330_Fig04-10.jpg

Figure 4-10. Selected elements are highlighted with light blue background and table records are underlined

4-11. Adding the Previous Set of Elements to the Current Set

Problem

You want to add the previous set of selected elements to the current set.

Solution

The following example of jQuery syntax adds the previous set of selected elements to the current set of selected elements.

$(selector1).selectionMethod().addBack(selector2)

selector2 is optional. If it is specified, elements from previous selection are matched against this selector before adding them back to the composite selection. Listing 4-11 demonstrates the use of the addBack() method to merge the previous and current selections.

Listing 4-11. Using addBack() method to merge the previous and current selections

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
      .tblHdr {
         background-color: lightgray;
      }
      .newRecord {
         background-color: lightyellow;
      }
      .listDepartments {
         width: 200px;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            $(".newRecord").nextAll().addBack().css("background-color", "lightblue");
         });
      });
   </script>
</head>
<body>
   <strong>Employees:</strong>
   <table class="listEmployees">
      <tr class="tblHdr">
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr class="newRecord">
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Customer Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <input id="btnTestIt" type="button" value="Test It">
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags. When the Test It button is clicked, the following code is executed:

$(".newRecord").nextAll().addBack().css("background-color", "lightblue");

$(".newRecord") selects all the HTML elements with the class name newRecord and returns a jQuery object. The <tr class="newRecord"> element is selected.

.nextAll("") selects all the following sibling HTML elements of the selected element, which is all the "tr" elements following the "tr" element but not including it.

.addBack() adds the previous selection (tr with the class name newRecord) to the set of currently selected elements.

css("background-color", "lightblue") changes the background color of the selected elements to light blue.

When you press the Test It button, the button’s click event handler changes the background color of the "tr" element with the class name newRecord, as well as all of its siblings, to light blue. Figure 4-11 displays the background color of the selected elements.

9781430264330_Fig04-11.jpg

Figure 4-11. Selected elements are highlighted with light blue

4-12. Creating a New jQuery Object from an Existing jQuery Object Using a Function

Problem

You want to create a new jQuery object based on each element of a set of selected elements using a function. The new jQuery object can contain the same element as the current one, a different element based on the attribute or property of current element, or no element at all.

Solution

The following example of jQuery syntax creates a new jQuery object from an existing one using the return value of the function.

$(selector).map(function() {  ... return(element) })

It returns the jQuery object. Each element from the set of selected elements is mapped to some other (or the same) element. If you don’t want to add an element for the current selected element, return null. Listing 4-12 demonstrates the use of the jQuery method map() to create a new jQuery object using mapped elements.

Listing 4-12. Using the map() method and function to create a new jQuery object

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <script src="scripts/jquery-2.1.0.min.js"></script>
   <style>
      table {
         border:3px double green;
      }
      .highlight {
         background-color: yellow;
      }
   </style>
   <script>
      $(function(){
         $("#btnTestIt").click(function () {
            var jqObj = $("tr:gt(0)").map(function() {
               return $(this).children().first().text();
            })
            var employeesName = jqObj.get().join(", ");
            $("#message").prop("innerHTML", "<strong>Employees List: "+ employeesName + "</strong>");
        });
      });
   </script>
</head>
<body>
   <table id="tblEmployee">
      <tr>
         <td>Employee Name</td><td>Department Name</td><td>Salary</td>
      </tr>
      <tr>
         <td>Jane Smith</td><td>Marketing</td><td>$95,000</td>
      </tr>
      <tr>
         <td>John Smith</td><td>Technology</td><td>$90,000</td>
      </tr>
      <tr>
         <td>Brian Adam</td><td>Sales</td><td>$72,000</td>
      </tr>
      <tr>
         <td>Mary Jones</td><td>Support</td><td>$60,000</td>
      </tr>
      <tr>
         <td>Michael Jefferson</td><td>Technology</td><td>$85,000</td>
      </tr>
   </table><br>
   <input id="btnTestIt" type="button" value="Test It"><br><br>
   <div id="message" class="highlight"></div>
</body>
</html>

How It Works

In this code, the employee details—employee name, department name, and salary—are listed in tabular form using the <table>, <tr>, and <td> HTML tags. When the Test It button is clicked, the following code is executed:

var jqObj = $("tr:gt(0)").map(function() {
   return $(this).children().first().text();
})
   var employeesName = jqObj.get().join(", ");
   $("#message").prop("innerHTML", "<strong>Employees List: "+ employeesName + "</strong>");

$("tr:gt(0)") selects all the HTML elements with the tag name "tr" except for the first record and returns the jQuery object.

.map() iterates through each element from the set of selected elements and processes them in the function.

return $(this).children().first().text() returns the text content of the first child element (td) of each selected "tr" element, which is the employee name.

A new jQuery object (jqObj) is created that contains elements as a result of the return value of the function.

jqObj.get() gets all the HTML elements from the jQuery object as an array.

.join(", ") joins all elements from the array, delimits them with commas (,) and returns a string that contains a comma-delimited list of all the employees’ names.

$("#message").prop("innerHTML", "<strong>Employees List: "+ employeesName + "</strong>") sets the innerHTML of the element with id set to "message", which is a div tag with the list of employees’ names.

When you press the Test It button, the button’s click event handler gets the employees list and displays it. Figure 4-12 displays the employees list.

9781430264330_Fig04-12.jpg

Figure 4-12. Employees names are selected and displayed

Summary

This chapter covered jQuery selectors filtering and expansion methods. To access the attributes, properties, text content, and HTML content of HTML elements or to change the value of their attributes and properties, you first need to select them by using id, className, attributeName, attributeValue, and so on. Then if needed, you fine-tune the set of selected elements by using the filtering and expansion methods. This chapter covered the following filtering and expansion methods:

  • Commonly used methods to filter (narrow down) the set of selected HTML elements are:
    • eq(indexNumber)
    • first()
    • last()
    • filter(selector)
    • not(selector)
    • slice(startIndex, endIndex)
  • The method to expand the set of selected HTML elements is add()
  • Other methods you saw in this chapter, all of which are covered in detail in Chapter 6, are:
    • get()
    • text()
    • css()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.150.231