O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.2. Reducing the Selection Set to a Specified Item

Problem

A jQuery selector is broad and selects all elements on the page based on your query. The need may rise when you need to select a single item, based on its position, but there isn’t an easy way to select that item without editing the code.

Solution

After you make your selection with jQuery, you can chain the .eq() method and pass in the index of the selection you want to work with.

Note

The selection index is zero-based, so the first item in the selection would be $().eq(0); where 0 represents the first item in the selection. $().eq(4); represents the fifth item.

Let’s use the end of the season standings for the National Hockey League (NHL) conferences as an example of how we can show which teams made the playoffs and which didn’t. What we need to do is list all the teams in each conference in the order they finished the season in. Since the top eight teams in each conference make it to the playoff round, we just need to figure out the eighth entry in each list and draw a line:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>Chapter 3 - Recipe 2 - Reducing the selection set to specified item</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required