CSS selector by id And some classes

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 supposed behavior or bug in Selenium? I quickly looked at the error tracker in Selenium, but I did not see anything about it. I wanted to ask here before raising a question that should not be. Also, as I understand it, it does not work in IE6, but who cares. I used firefox for this run.

+8
css-selectors selenium-webdriver
source share
2 answers

findElement() finds the element in the current context, which means that your first piece of code does indeed find the element that matches the .aClass.andAnother input[type=text] that is contained in #someId . An element with this identifier may or may not contain two classes; WebDriver does not assume that you are referring to the same element; it just finds input while its ancestors #someId and .aClass.andAnother .

This is completely different from div#someId.aClass.andAnother input[type=text] , which finds only input[type=text] inside div#someId.aClass.andAnother (i.e. a div that contains both an identifier and classes).

+7
source share

In fact, the two are completely different selectors.

Here is your cssSelector:

 div#someId.aClass.andAnother input[type=text] 

But you really wanted to write:

 div#someId .aClass.andAnother input[type=text] 

note the space between the identifier and the class. You need it.

+11
source share

All Articles