1

There is a great discussion on what makes a good Selenium locator here.

It seems many testers prefer CSS to XPath for locators, for various reasons. And that goes for me, too.

But, it is often very convenient to use XPath's //*[contains(.,'some text')], especially when selecting dynamic elements from a table. For example, you wish to enter a new element to a table and click a button next to it. You can make a generic locator of type "//*[contains(.,"'+new_element_name+'")]/button".

How can you do that without using XPath?

1

There is no CSS way to find an element by its text, unless you inject jQuery into the page.

Personally I do not see any issue with using XPaths to find elements containing a text. I would consider adding classes or id's to the elements you are trying to find.

For the button part, I think you are looking to find childs within a CSS query:

div:contains('new_element_name') > button
  • Isn't that a jQuery locator? It doesn't work with pure CSS, e.g. in DevTools. – Mate Mrše Apr 5 at 8:41
  • It is about the > use any valid css selector to find the first element, but will change it to a more pure css thing – Niels van Reijmersdal Apr 5 at 8:43
  • But you are right, the :contains() has been removed from CSS, it used to be part of the CSS3 spec. – Niels van Reijmersdal Apr 5 at 8:45
  • Hmm oke, finding an element by text is more complex, but I didnt think that was your question – Niels van Reijmersdal Apr 5 at 8:52
  • I am specifically interested in finding an element by containing text since there are many people claiming they prefer CSS to XPath (see the linked question). So I am curious in how do they do it. – Mate Mrše Apr 5 at 9:08
1

When there really is no better way, you can always find all elements and search for the text

driver.findElements(By.cssSelector("button")).stream()
      .filter(e -> e.getText().contains("search text"))
      .findFirst();
1

There isn't a contains() option for CSS, but you do still have:

Starts With ^=

Ends with $=

e.g.

By element = By.cssSelector("div[class^='logo-name']");

= Will match anything that starts with "logo-name".

So you can usually make use of that to still find the element (as it's likely you know the start or end and are just trying to find an element that is appending a prefix / suffix).

  • Nice. This is useful, but I wish to select the element by containing text. – Mate Mrše Apr 16 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.