Joe Lloyd
Joe Lloyd

Reputation: 22513

Can I get a web element inside another web element?

Yo dawg I heard you like web elements...

So I would like to know if it is possible to find a web element by class, id or any other selector and then inside that find another element by class etc.

Background

I have some container with an id that contains a collection of elements I want to put into a list by class, the problem is that if I try to getElements(By.class) it will pick up some elements outside that I don't want.

Attempted

I have tried doing it with XPATHbut it feels dirty like hard coding. Since these tests should be robust I thought there must be a better way of doing it.

This code captures elements outside of what I want

public double checkStars(){
    List<WebElement> starsOn = driver.findElements(By.className("on"));
    return starsOn.size();
}

Question

Can I select a web element when limiting the search to inside another web element and how is it done?

Upvotes: 3

Views: 3368

Answers (2)

JeffC
JeffC

Reputation: 25744

You should take a look at CSS selectors. It's generally a faster way of accomplishing this. Here's a simple example for the google.com page. It grabs the two links (A tags) in the upper right, Gmail and Images.

FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
List<WebElement> links = driver.findElements(By.cssSelector("#gbw a.gb_P"));
for (WebElement link : links)
{
    System.out.println(link.getText().trim());
}

This CSS selector, #gbw a.gb_P, reads as find an element with an id (#) gbw that has descendant A tags with class (.) gb_P. CSS selectors are very powerful tools can do pretty complex stuff and are faster and less brittle (in general) than XPaths.

CSS Selector reference

Upvotes: 1

Mrunal Gosar
Mrunal Gosar

Reputation: 4683

Yes. You can find another element inside an element provided that element is child element of that element. something like this:

WebElement eleParent=driver.findElement(Locator);
WebElement eleChild=eleParent.findElement(Locator);

Be careful if your locator is XPath !!!

Upvotes: 3

Related Questions