jQuery :nth-of-type() Selector

The jQuery :nth-of-type() Selector selects all the items of their parent of the specified element type. You can select the required element by specifying the position of the element.

jQuery :nth-of-type() Selector

Syntax of jQuery :nth-of-type() Selector

The syntax of jQuery :nth-of-type() selector is given below.

Syntax
$(“:nth-of-type(number|even|odd|equation)”)

The selector requires a position value as an argument to pass to the selector. To select the specific type element, you have to specify the tag name of the element before the selector name.

The description of the parameters given below.

Description of Parameters

Parameter Name Description
number A number is the index position of the element which starts from 1 for the group element.
even If you want to select the even elements, you have to use this keyword as an argument. It selects the elements placed at positions 0, 2, 4,…n.
odd It selects odd elements placed at positions 1, 3, 5,…n.
equation You can derive the equation using the formula an+b. Let’s take an example:- if you want to select elements present at positions 0, 2, 4,…n. Use the equation 2n as the formula to specify as an argument of the selector. To solve the equation, you have to put the value of n as 0,1,2,…n to get the output as positions of the elements.

jQuery :nth-of-type() Selector Select Specified Table Row

Suppose you have to select the second span element of every cell. For doing this, you have to specify and use the selector as the example given below.

It specifies the selector span:nth-of-type(2) to select the matching cells contains the element. There are two span elements inside the second cell of each rows of a table.

Example

Test it Live

Output

Motor Vehicle Price
Car 2 Lac
Tractor 4 Lac
Gypsi 8 Lac
Maruti 3 Lac
Truck 15 Lac

You have to click the button given in the example above to select the 2nd span element of table cells. It applies the ‘red’ color to the selected element after you click the button.

Select the List Items of the Same Type Using the Selector

If you want to select the second item of the list element, you have to specify and use the selector as given in the example below. It contains five items and the selector selects the second item of list element.

Example

Test it Live

Output

  • Truck
  • Bike
  • Omni
  • Auto-Ricksaw
  • Bus

Click the button provided in the example above to select the second list item. A background color is added to the 2nd list item when you click the button. Apply other effects of jQuery by selecting the element using the above method.

I hope you like this tutorial of jQuery :nth-of-type selector to select all elements of matching type. If you have any queries regarding the tutorial, please comment below.

Also tell me, what other methods you are using with the selector by commenting below.

References