05 – Selecting elements using child filters in jQuery

You can select elements in jQuery using CSS3 child pseudo-classes based on their position inside a parent element.

A few examples:

  • The ul li:last-child selects the last <li> of each <ul> element.
  • The div p:nth-child(2) retrieves all <p> elements inside a <div> that are the second child.
  • The div .main-div:nth-of-type(3) retrieves all the third elements having class main-div inside a <div>.

Note:

  • The :nth-child() counts all children elements regardless of their type and the index starts from 1 instead of 0.
  • The :eq() selects only the elements corresponding to the selector attached to the pseudo-class, regardless of how many siblings they have before them and the index starts from 0.

There are many available selectors and most of them allow for more syntaxes and they can accept different type of parameters. For example, :nth-child(), :nth-last-child(), :nth-last-of-type(), and :nth-of-type() can accept as parameters the word “even,” the word “odd,” or an equation (you can have an unknown variable as n).

Here you have a list of the child filters of jQuery:

  • :first-child – Matches the first child element
  • :last-child – Matches the last child element
  • :first-of-type – Matches the first child element of the given type
  • :last-of-type – Matches the last child element of the given type
  • :nth-child(n) – Matches the nth child element
  • :nth-child(even|odd) – Matches even or odd child elements
  • :nth-child(Xn+Y) – Matches nth child elements based on the formula
  • :nth-last-child(n) – Matches the nth child element (from last to first)
  • :nth-last-child(even|odd) – Matches even or odd child elements (from last to first)
  • :nth-last-child(Xn+Y) – Matches nth child elements based on the formula (from last to first)
  • :nth-of-type(n) – Matches the nth child element (in relation to siblings with the same element name)
  • :nth-of-type(even|odd) – Matches even or odd child elements (in relation to siblings with the same element name)
  • :nth-of-type(Xn+Y) – Matches nth child elements based on the formula (in relation to siblings with the same element name)
  • :nth-last-of-type(n) – Matches the nth child element (in relation to siblings with the same element name; from last to first)
  • :nth-last-of-type(even|odd) – Matches even or odd child elements (in relation to siblings with the same element name; from last to first)
  • :nth-last-of-type(Xn+Y) – Matches nth child elements based on the formula (in relation to siblings with the same element name; from last to first)
  • :only-child – Matches the elements that have no siblings
  • :only-of-type – Matches the elements that have no siblings of the same type

If you target an element at any position that’s a multiple of 3 (for example 3, 6, 9, etc), you have to write 3n, at a position that’s a multiple of 3 plus 1 (for example 1, 4, 7, etc), you have to write 3n+1.

Leave a Reply