Selecting Elements by Index Order - J Query

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

Solution

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:

:first
Matches the first selected element
:last
Matches the last selected element
:even
Matches even elements (zero-indexed)
:odd
Matches odd elements (zero-indexed)
:eq(n)
Matches a single element by its index (n)
:lt(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).

Selecting-Elements-by-Index-Order(1)

Figure : Table with even rows darkened

Discussion

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 DMCA.com Protection Status

J Query Topics