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!')]
.
Asked
Active
Viewed 2,466 times
2

BoltClock
- 700,868
- 160
- 1,392
- 1,356

Randomblue
- 112,777
- 145
- 353
- 547
1 Answers
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.
-
`contains(@class, 'myClass')` also matches `AmyClassman`. It's better to use something like `contains(concat(' ', @class, ' '), ' myClass ')` – Wayne Jan 25 '12 at 16:19
-
@lwburk: I was hoping for a solution around that. Thanks! I've updated my answer. – BoltClock Jan 25 '12 at 16:29