CSS nth-child Selector

In CSS Selector, we have a very useful structural pseudo-class selector i.e. ‘nth-child’ selector. ‘nth-child’ can be used to select ordered elements by giving the expression (an+b) or single element with positive integer as an argument. Consider if you want to get odd rows from a HTML table using Selenium WebDriver, your immediate idea will be ‘separating odd rows using FOR loop’. But we can accomplish it using nth-child (2n+1) selector.

nth-child (2n+1) expanded below.
(2*0) + 1=1=1st Row
(2*1) + 1=3=3rd Row
(2*2) + 1=5=5th Row

Selenium WebDriver-Java code below counts no. of odd rows in a table.

The below code gets first row from a table.


Browser Compatibility

IE9+, FF 11.0+ on Win, FF 10.0.2+ on Mac, Safari 5.1, Chrome 18+ on Win and Chrome 17+ Mac.

[Total: 3    Average: 5/5]