All the examples of findElement(By.xpath) I've seen search the whole page, e.g.
WebElement td = driver.findElement(By.xpath("//td[3]"));
What I want to achieve is this:
WebElement tr = ... // find a particular table row (no problem here)
WebElement td = tr.findElement(By.xpath("/td[3]")); // Doesn't work!
I've also tried other variations without luck: "td[3]", "child::td[3]"
Using "//td[3]" finds the first matching node in the whole page, i.e. not restricted to my tr. So it's looking like when you findElement by xpath, the WebElement on which you call findElement() counts for nothing.
Is it possible to scope findElement(By.xpath) to a particular WebElement?
(I'm using Chrome, in case it matters.)
PLEASE NOTE: By.xpath("//td[3]") is just an example. I'm not looking for alternative ways of achieving the same thing. The question is just about trying to ascertain whether foo.findElement() takes any notice of foo when used with a By.xpath selector.
Based on ZzZ's answer I think the issue is that the queries you are trying are absolute instead of relative. By using a starting /
you force absolute search. Instead use the tag name as ZzZ suggested, ./
or .//
.
Look in the XPath docs under "Location Path Expression"
I also ran into this issue and spent quite a lot of time trying to figure out the workaround. And this is what I figured out:
WebElement td = tr.findElement(By.xpath("td[3]"));
Not sure why, but this works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With