Using selenium for the first time here, I was wondering why:
final WebElement justAnId = findElement(By.cssSelector("#someId"));
final WebElement whatIWant = justAnId.findElement(
By.cssSelector(".aClass.andAnother input[type=text]")
);
works, but not:
final WebElement whatIWant = findElement(By.cssSelector(
"div#someId.aClass.andAnother input[type=text]"
));
Although they seem equivalent to me I get:
org.openqa.selenium.NoSuchElementException: Unable to locate element:
{"method":"css selector","selector":"div#someId.aClass.andAnother input[type=text]"}
Is this intended behaviour or a bug in Selenium? I had a quick look in the bug tracker in Selenium but I didn’t see anything about that. I wanted to ask here before raising an issue that doesn’t need to be. Also as far as I understand it doesn’t work in IE6 but who cares. I was using firefox for this run.
findElement()finds an element in the current context, which means your first snippet of code is really finding an element that matches.aClass.andAnother input[type=text], which is contained within#someId. The element with that ID may or may not contain the two classes; WebDriver doesn’t assume you’re referring to the same element; it just finds theinputas long as its ancestors are#someIdand.aClass.andAnother.This is completely different from
div#someId.aClass.andAnother input[type=text], which finds anyinput[type=text]withindiv#someId.aClass.andAnotheronly (i.e. it’s adivthat contains both the ID and the classes).