Finding elements using advanced CSS selectors

We saw some basic CSS selectors in earlier recipes. In this recipe, we will explore some advanced CSS selectors for finding elements.

How to do it...

In the Finding elements using CSS selectors recipe, we explored some basic CSS selectors. Let's explore advanced CSS selectors such as adjacent sibling combinators and pseudo-classes, as described in the following sections.

Finding child elements

The CSS selectors provide various ways to find child elements from parent elements.

For example, to find the Username field in the login form, we can use the following selector. Here, > is used denote the parent and child relationship:

WebElement userName = driver.findElement(By.cssSelector("form#loginForm > input"));

Similarly, the nth-child() method can be used in the following way:

WebElement userName = driver.findElement(By.cssSelector("form#loginForm :nth-child(2)"));

Here, the second element in <form> is the Username field. The following table shows some of the structural pseudo-classes used to find child elements:

Finding sibling elements

With the CSS selector, we can find sibling elements using the + operator. For example, on the sample page, the <p> element with the Description for Product 2 text is selected in the following way:

WebElement productDescription = driver.findElement(By.cssSelector("div#top5 > p + p"));

In this example, the first child of div#top5 will be <p> with Description for Product 1 and its immediate sibling will be Description for Product 2. Here are a few more adjacent sibling combinations for finding siblings:

Using user action pseudo-classes

Using the user action :focus pseudo-class, we can find an element which currently has the input focus in the following way:

WebElement productDescription = driver.findElement(By.cssSelector("input:focus"));

This will locate any element that currently has the input focus. You can also find elements using the :hover and :active pseudo-classes.

Using UI state pseudo-classes

Using UI state pseudo-classes, we can find elements for various states, such as when control is enabled, disabled, and checked. The following table describes these in detail:

How it works...

Apart from the basic CSS selectors, you can also use various advanced CSS selector methods such as pseudo-classes or adjacent sibling combinators to find the elements with Selenium WebDriver API.

Visit http://www.w3schools.com/cssref/css_selectors.asp for an exhaustive list of CSS selectors and their usage.

See also

  • The Finding elements using CSS selectors recipe