10

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.

2 Answers 2

11

Actually the two are quite different selectors.

Here is your cssSelector:

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

But what you really wanted to write was:

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

notice the space between ID and class. you need that.

Sign up to request clarification or add additional context in comments.

Comments

8

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 the input as long as its ancestors are #someId and .aClass.andAnother.

This is completely different from div#someId.aClass.andAnother input[type=text], which finds any input[type=text] within div#someId.aClass.andAnother only (i.e. it's a div that contains both the ID and the classes).

2 Comments

+1 on this answer. As a sanity check, whenever you encounter an issue like this in WebDriver, open the browser's JavaScript console (Firebug for Firefox, the F12 Developer Tools for IE, and the WebKit Developer Tools for Chrome) and use document.querySelector() using the same selector that failed for you in your WebDriver code. If the selector doesn't return the expected element in the JavaScript console, you can be sure it'll never do so in WebDriver.
Thanks for the answer and comments, I didn't know I could use the selectors from the dev tools, +1. Ren.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.