user3356141
user3356141

Reputation: 501

XPath OR operator on multiple different elements

I have two elements that cannot be on the same page together. I want to make one Xpath Selector that checks for either Element A, OR element B:

Element A: //div[contains(@class, 'A')]//button[@name='Name123']

Element B: //div[contains(@class, 'B')]//button[@name='Name123']

I thought it would work something in the line of

("(//div[contains(@class, 'A')]//button[@name='Name123']) OR 
(//div[contains(@class, 'B')]//button[@name='Name123'])")

But that is not a valid XPath expression.

What am I doing wrong?

Upvotes: 1

Views: 2680

Answers (3)

Michael Kay
Michael Kay

Reputation: 163322

Note that if there are many div elements whose class contains 'A' or 'B', but few button elements whose @name is 'Name123', then the following may be more efficient:

//button[@name='Name123'][ancestor::div[@class[contains(.,'A') or contains(., 'B')]]

But of course this is implementation-dependent.

Upvotes: 1

srk
srk

Reputation: 1901

Try this xpath:

//div[contains(@class, 'A') or contains(@class, 'B')]//button[@name='Name123']

Upvotes: 3

Somber
Somber

Reputation: 443

Get rid of extra bracers and replace OR with | then it is going to happen.

Driver.FindElement(By.XPath("//div[contains(@class, 'A')]//button[@name='Name123'] | //div[contains(@class, 'B')]//button[@name='Name123']"));

Upvotes: 3

Related Questions