Reducing the Selection Set to a Specified Item - J Query

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.
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 did n’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 play off round, we just need to figure out the eighth entry in each list and draw a line:

Reducing-the-Selection-Set-to-a-Specified-Item

Figure : shows the code output.

As you can see, we just use an ordered list to list the teams in the order they placed, then we use jQuery to add a bottom border to the eighth item in each list. We need to add an ID to each ordered list so that we can specify each list in a separate query. If we were to do $("li").eq(7);, it would select only from the first list because the query would have counted all the <li>elements on the page together.

Discussion

The .eq() method is used to take a selection set and reduce it to a single item from that set. The argument is the index that you want to reduce your selection to. The index starts at 0 and goes to length −1. If the argument is an invalid index, the method will return an empty set of elements instead of null.
The .eq() method is similar to using the $(":eq()"); right in your selection, but the .eq() method allows you to chain to the selection and fine-tune further. For example:

This will change the background color of all <li>elements and then select the first one and give it a different color to signify that it is perhaps a header item.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics