jQuery :nth-child selector
The :nth-child() selector is used to match the elements based on their position regardless of the type of its parent. This selector is used to match the elements based on their position within a group of siblings. It matches each element, which is the nth-child.
We can use the :nth-of-type selector if we have to select the elements that are the nth-child of a particular type of their parent.
The syntax of using the :nth-child selector is given as follows.
The values mentioned in the above syntax are defined as follows.
n: The n in the above syntax must be an integer. It represents the index of each child to match. This parameter indicates the selector to select the child present at the specified index value. The index number of the first element is 1.
odd: It selects every odd child element.
even: It selects every even child element.
formula: It selects the child element present at the value of the formula. The formula for finding the different children is an+b.
If we consider a = 2 and b = 1, the formula will be 2n+1, which will only select the elements present at the index value 1, 3, 5, ..…index. To solve the formula, we can put the value of n as 0, 1, 2, ….n.
Now, let's see an example of using all the parameter values of the :nth-child selector.
In this example, we are using all parameter values of the :nth-child selector. There are ten list items starting from 1 to 10, and four buttons named as :nth-child(7), Odd, Even, and nth-child(4n+4). The first button will select the list item with index number 7, the second button will select the odd list items, the third button will select the even list items, and the fourth button will select the list items present at index value 4 and 8.
We have to click the given buttons to see the effect.Test it Now
After the execution of the above code, the output will be -
After clicking the first button, the list item with index 7 will get selected as shown below -
After clicking the second button, all odd list items will get selected as shown below -
After clicking the third button, all even list items will get selected as shown below -
After clicking the fourth button, the list items with index value 4 and 8 will get selected as shown below -