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.
Multiple classes can be applied to a single element in HTML and they can be styled using CSS.
Type “css=input[type='submit']” (locator value) in Selenium IDE. Click on the Find Button. The “Sign in” button will be highlighted, verifying the locator value. Attribute: Used to create the CSS Selector.
We can find elements by multiple class names. If there is an element having more than one value separated by spaces set for the class attributes, it is called the compound class names. We shall get an exception if we use both the values - toc and chapters with the class name locator for the above scenario.
Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names. Here is the HTML for the examples in this article.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With