jQuery :nth-child() Selector

The jQuery nth-child() selector selects all the elements for the specified nth-child of the parent. By using the selector, you can select the required elements by specifying its position as the selector argument.

jQuery nth-child Selector image

Let’s start with the syntax of the selector.

Syntax of jQuery :nth-child() Selector

The syntax of jQuery :nth-child selector is given below.

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

It require an ara parameter to specify and select the element. The description of the parameters are given below.

Description of Parameters

Parameter Name Description
number It is the position of the element that you want to select which starts from 1 for the group elements.
even To select the even items of the group elements like table and list.
odd Select odd items of the group elements like table and list.
equation Place an equation by using the formula an+b to select the elements. For example if you place 2n+1, it select elements of index 1, 3, 5,…index. You can solve the equation by putting the value of n as 0,1,2,…n.

jQuery :nth-child Selector Select Even Rows of a Table

If you want to select the even rows of the table, you have to specify the keyword even as the argument of the selector. You can also specify the equation 2n as the argument of the selector to select the even items.

See the example below to select the element on the click event of a mouse.

Example

Test it Live

Output

Sr No Name
1 Selector
2 Attributes
3 Events
4 Effects
5 Core Functionality

The above example contains a table and a button. You have to click the button to select the even rows of the table. It applies the background color as ‘yellow’ to highlight the selected rows of the table.

Select Odd Elements of List Using the Selector

A list is also a group element to which you can apply the selector to select odd items. After selecting the element, you can apply the color and other effects of jQuery.

Example

Test it Live

Output

  • jQuery Selectors
  • PHP Functions
  • CSS Properties
  • SQL Queries

The above example selects the odd list items when you click the button given above. It applies the ‘red’ color to the text of the list items onclick.

You can find this selector useful when you want to select your website menu items to improve the design. It can also be useful when you want to highlight alternate table rows.

I hope you like this tutorial of jQuery :nth-child selector to select all end items. 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

One reply on “jQuery :nth-child() Selector”

  1. “It require a argument to specified and select the element.”? What kind of grammar is that?
    Not a bad tutorial, though. 🙂

Comments are closed.