The Power of jQuery Selectors: Selecting by Position

Elements can also be selected by their relation to other elements (child/parent relationships), or by hierarchical position in a document. Some examples might include selecting the first or last items in a list, or the even rows in a table. Suppose you have an ordered list like the one in the following code snippet. It presents an ordered list of “fowl.” The JavaScript that follows illustrates several variations on jQuery’s selectors by position. They resolve as follows:

  • li:even returns the even numbered members of the matched set.
  • li:odd returns the even numbered members of the matched set.
  • li:first returns the first element of the matched set.
  • li:last returns the last element of the matched set.
  • li:eq(3) returns the 4th element in the matched set.
  • li:gt(2) returns all elements of index greater than 2 in the matched set.
  • li:lt(3) returns all elements of index less than 3 in the matched set.

Note that all position selectors start their count at zero except for the nth-child filter, which starts at 1, which we’ll explain in the section on “Filtering by Relationships.”

<ol id=”fowl”>

<li>Turkey</li> <!– 0 –>
<li>Chicken</li> <!– 1 –>
<li>Parrot</li> <!– 2 –>
<li>Pigeon</li> <!– 3 –>
<li>Hawk</li> <!– 4 –>

</ol>
$(“li:even”)  // returns turkey, parrot, and hawk
$(“li:odd”)   // returns chicken and pigeon
$(“li:first”) // returns turkey
$(“li:last”)  // returns hawk
$(“li:eq(3)”) // returns pigeon
$(“li:gt(2)”) // returns pigeon and hawk
$(“li:lt(3)”) // returns parrot, chicken, turkey.

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *