Selecting Elements by Index Order - J Query

You need to select elements based on their order among other elements.


Depending on what you want to do, you have the following filters at your disposal.
These may look like CSS pseudo classes, but in jQuery they’re called filters:

Matches the first selected element
Matches the last selected element
Matches even elements (zero-indexed)
Matches odd elements (zero-indexed)
Matches a single element by its index (n)
Matches all elements with an index below n:gt(n)
Matches all elements with an index above n
Assuming the following HTML markup:

the first item in the list could be selected in a number of different ways:

Notice that both the eq() and lt() filters accept a number; since it’s zero-indexed, thefirst item is 0, the second is 1, etc.
A common requirement is to have alternating styles on table rows; this can be achievedwith the :even and :odd filters:

You can apply a different class dependent on the index of each table row:

You’d have to specify the corresponding class (even) in your CSS style sheet:

This code would produce the effect shown in Figure (Table with even rows darkened).


Figure : Table with even rows darkened


As mentioned, an element’s index is zero-based, so if an element is the first one, then its index is zero. Apart from that fact, using the preceding filters is very simple. Another thing to note is that these filters require a collection to match against; the index can be determined only if an initial collection is specified. So, this selector wouldn’t work:
jQuery(':even'); An initial collection is required on the left hand side of the filter, i.e., something to apply the filter to. The collection can be within an already instantiated jQuery object, as shown here:

The filter method is being run on an already instantiated jQuery object (containing the list items).

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

J Query Topics