Select Page
Selenium

CSS nth-child Selector

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.

XPath vs CSS Selectors

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.

int inCount=driver.findElements(By.cssSelector("table[id='tbl1'] tr:nth-child(2n+1)")).size();
  

The below code gets first row from a table.

WebElement firstRow=driver.findElement(By.cssSelector("table[id='tbl1'] tr:nth-child(1)"));
  

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.

Comments(0)

Submit a Comment

Your email address will not be published. Required fields are marked *

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility