Selenium Tips: Finding elements by their inner text using :contains, a CSS pseudo-class

Posted by Santiago Suarez Ordoñez in SeleniumSelenium Resources

As 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 XPATH. That's why for this Tip of the Week, we are presenting our users one more CSS pseudo-class to keep moving their test suites to this faster and cleaner location strategy. Let's imagine you have an element like the following:

<div>Click here</div>

The easiest way to locate it is using it's "Click here" inner text and in XPATH you would do it using XPATH's text() function:

//div[text() = "Click here"]

or even better (because the previous version can sometimes fail depending on the browser):

//div[contains(text(), "Click here")]

Now, if you want to move your locators to CSS in situations like this one, all you have to do is use the :contains() pseudo-class, with which your tests would end up using the following locator:

css=div:contains("Click here")

Did you find this useful? Are you still fighting with another XPATH functionality to completely move your tests to CSS? Let us know about it in the comments.

Interested in learning how to use Selenium for your automated testing? Check out Sauce Labs Selenium courses.

Discuss: Selenium Tips: Finding elements by their inner text using :contains, a CSS pseudo-class
0 Comments

Free Trial

Get access to a free 14-day trial version, or contact Sales for more information.