JCB
JCB

Reputation: 401

How can I create an XPath that will look for button text or text from a nested element within the button?

I am using Selenium web driver in order to test out a button and this button can either have text like so

<button>Foo</button>

Or it can look like this with nested tags of any type or depth.

<button><span>Foo</span></button>

I tried doing

Driver.findElement(By.xpath("//*[text()='Foo']")); 

But this would only get the text in the immediate tag level. I added a “//*” to the xpath and it would work for the nested element but then stop working for when the text is in the immediate level. I am looking for kind of OR condition or something where I can get this to work on both variations.

I am using Java and selenium web driver.

Thanks in Advance,

Juan

Upvotes: 4

Views: 2058

Answers (1)

Prophet
Prophet

Reputation: 33381

Try this:

driver.findElement(By.xpath("//button[contains(.,'Foo')]")); 

This will search for button element containing Foo text content in itself or any it child, exactly what you asking for.
BTW in Java we normally give objects names starting with non-capital letter, so it should be driver, not Driver there.

Upvotes: 3

Related Questions