Following my previous TOTW about improving your locators, this blog post will show you some advanced CSS rules and pseudo-classes that will help you move your XPATH locators to CSS, a native approach on all browsers.
Next sibling
Our first example is useful for navigating lists of elements, such as forms or ul items. The next sibling will tell selenium to find the next adjacent element on the page that’s inside the same parent. Let’s show an example using a form to select the field after username.
Let’s write a css selector that will choose the input field after “username”. This will select the “alias” input, or will select a different element if the form is reordered.
css=form input.username + input
Attribute values
If you don’t care about the ordering of child elements, you can use an attribute selector in selenium to choose elements based on any attribute value. A good example would be choosing the ‘username’ element of the form without adding a class.
We can easily select the username element without adding a class or an id to the element.
css=form input[name='username']
We can even chain filters to be more specific with our selections.
css=input[name='continue'][type='button']
Here Selenium will act on the input field with name=”continue” and type=”button”
Choosing a specific match
CSS selectors in Selenium allow us to navigate lists with more finess that the above methods. If we have a ul and we want to select its fourth li element without regard to any other elements, we should use nth-child or nth-of-type.
-
<p>Heading</p>
- Cat
- Dog
- Car
- Goat
If we want to select the fourth li element (Goat) in this list, we can use the nth-of-type, which will find the fourth li in the list.
css=ul#recordlist li:nth-of-type(4)
On the other hand, if we want to get the fourth element only if it is a li element, we can use a filtered nth-child which will select (Car) in this case.
css=ul#recordlist li:nth-child(4)
Note, if you don’t specify a child type for nth-child it will allow you to select the fourth child without regard to type. This may be useful in testing css layout in selenium.
css=ul#recordlist *:nth-child(4)
Sub-string matches
CSS in Selenium has an interesting feature of allowing partial string matches using ^=, $=, or *=. I’ll define them, then show an example of each:
| ^= | Match a prefix |
| $= | Match a suffix |
| *= | Match a substring |
css=a[id^='id_prefix_']
A link with an “id” that starts with the text “id_prefix_”
css=a[id$='_id_sufix']
A link with an “id” that ends with the text “_id_sufix”
css=a[id*='id_pattern']
A link with an “id” that contains the text “id_pattern”
Matching by inner text
And last, one of the more useful pseudo-classes, :contains() will match elements with the desired text block:
css=a:contains('Log Out')
This will find the log out button on your page no matter where it’s located. This is by far my favorite CSS selector and I find it greatly simplifies a lot of my test code.
Tune in next week for more Selenium Tips from Sauce Labs.
Sauce Labs created Sauce OnDemand, a Selenium-based testing service that allows you to test across multiple browsers in the cloud. With Selenium IDE and Selenium RC compatibilities, you can get complete cross-platform browser testing today.

Hey,
thank you very much. This is awesome.
Stay tuned. TK
Hello! Wonderful concept, but will this really perform?
Robert
Well, the best answer is that it really depends on each test and situation. But if your test requirements involve IE, it’s definitely worth a try.
@Hydrolyze
It is more than a try.
I’ve implemented these tips and I am impressed.
My testduration was with Xpath and IE (6,7,8) more than five minutes.
Now with the css locator instead of the Xpath the test duration is not more than a minute.
Conclusion: It will really perform. Just try it. You’ll be impressed.
TK
Is there a pseudo-classes selector to match exact inner text? Or another strategy?
JP
@JP:
Yeah, for finding elements depending on their inner text, you can use the following CSS pseudo class:
css=a:contains(“Inner Text”)
[...] we already mentioned in our previous posts CSS Selectors in Selenium Demystified and Start improving your locators, CSS as a location strategy generally far outperforms [...]
when i try to select nth element in a list of elements of same type using nth-type-of as shown in ur exmaple, its not working.
i wish it is not supported by selenium.Source
http://release.seleniumhq.org/selenium-core/1.0.1/reference.html
“Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after)”.
Guys, thanks for very useful post,
and I wonder what do you think how do we replace the XPATH: preceding-sibling
with CSS?
can someone give an example,
using the code from “Next sibling” in this article:
How to find the previous element if I know only the input “alias” element.
Thanks!
Is there a pseudo-classes selector to match exact inner text?
we can use a:contains(Text1) but if the element ‘a’ contains TempText1 as its text also will match
Hi,
For the following case,how to use the css selector?
cat
tiger
As there is a space between “mini” and “shared”,I try as following but all failure.
css=ul.mini shared li:nth-child(1)
css=ul.(mini shared) li:nth-child(1)
css=ul.[mini shared] li:nth-child(1)
Any idea?
Thanks!
2 strawberry:
You need to use the following syntax:
css=ul[class='mini'] shared li:nth-child(1)
Same situation with id, for example:
css=form#myId => css=form[id='myId']
2 strawberry again:
Sorry for the misprint, I meant
css=ul[class='mini shared'] li:nth-child(1)
of course.
It seems for me it’s time to go to sleep :)
regarding:
css=ul#recordlist li:nth-of-type(4)
I thought nth-of-type was not a supported pseudo class of selenium? I haven’t been able to get this to work.
Thanks Alex! It works now!
I’ve had the same experience as @kevin.
The :nth-of-type() pseudo-class doesn’t appear to be supported… so I’m confused as to why Sauce would be recommending it.
Hey @Santiago… care to comment?
I’d love to use this advice, but after trying it out in my tests, I got a bunch of failures. (See @uday’s comment above.)
What works in FireFinder/Firebug doesn’t always work in Selenium.
In my web page I have to occurrences of a row e.g.
14
18
I can refer to the first occurrence using:
selenium.GetText(“css=tr.tablerow_on td:nth-child(1)”)
How do I refer to the second occurrence e.g the td valued 18?
Looks like your code was escaped, try wrapping it within <code> tags.
Just guessing what your code is, I’d say it should be done using something like:
css=tr.tablerow_on td:nth-child(2)Did you try that?
What about matching an input with a prefix and a suffix. Say I had an input with ID prefix_somerandomsequence_suffix?
obviously css=input[id^='prefix_' id$='_suffix'] does not work but is there something similar?
Couldn’t try it yet, but I’d write it like the following:
css=input[id^='prefix_'][id$='_suffix']
Let us know if it works.
hi,
I am using selenium 1.0.1 and it does not seem to support nth-type.
I am using Java to write my tests.
Which version and coding language are you guys using
Thanks
Nidhi