2

Is it possible to specify a CSS selector inside an XPath? Essentially, I want to find elements that satisfy both .myClass div and div[contains(., 'Hello!')].

1 Answer 1

5

No, you can't combine CSS selector syntax and XPath syntax into a single expression. Neither language has any feature that lets you feed an expression from the other.

You can only incorporate the CSS selector into the XPath as XPath, which means you'll need to translate it yourself. In your case, here's the resultant XPath expression:

//*[contains(concat(' ', @class, ' '), ' myClass ')]//div[contains(., 'Hello!')]

Of course, this depends on what you can accomplish with CSS selectors or XPath. For example, if the :contains() pseudo-class hadn't been dropped from CSS3, you would have been able to use this CSS selector just as well:

.myClass div:contains('Hello!')

But it's been removed from the spec, so you'll only be able to get it to work as a jQuery selector or a Selenium CSS locator.

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

2 Comments

contains(@class, 'myClass') also matches AmyClassman. It's better to use something like contains(concat(' ', @class, ' '), ' myClass ')
@lwburk: I was hoping for a solution around that. Thanks! I've updated my answer.

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.