04 – Selecting elements by filtering their position in jQuery

With jQuery you have the ability to select elements of a web page by their position. For example if you want to select the first <a> on the page you will write:

a:first

If you want to retrieve links starting from the third one on the page you will write the following code:

a:gt(1)

The gt means “Greater Than”. The argument 1 is the index from which to start. If you have any kind of programming background you will know that indexes usually start at 0. So, greater than 1 means the third element!

Here you have the position filters supported by jQuery:

  • :first – Selects the first match (Example: li a:first returns the
    first anchor that’s a descendant of a list item).
  • :last – Selects the last match (Example: li a:last returns the
    last anchor that’s a descendant of a list item).
  • :even – Selects even elements (Example: li:even returns every
    even-indexed list item).
  • :odd – Selects odd elements (Example: li:odd returns every oddindexed list item).
  • :eq(n) – Selects the nth matching element (Example: p:eq(2) selects the paragraph at index 2).
  • :gt(n) – Selects elements after the nth matching element (Example: p:gt(2) selects the paragraph at index 3).
  • :lt(n) Selects elements before the nth matching element (Example: p:lt(2) selects the paragraph at index 1).

Note:
The :even and :odd are related to the index of the elements within the set.
You can pass a negative value to :eq(), :gt(), and :lt() so the counting starts from the last element.

Leave a Reply