Xpath / Getting the closest ancestor with some value

I want to get the closest ancestor WebElementwith some attribute.

For instance:

<div>
    <i value1= "hello">
       <a value1 = "bye">
          <div id="2"> Hello </div></a></i></div>

I have WebElmentin Jave, which representsdiv (id="2")

How can I get the closest parent that has an attribute value1?

In this case, I would get item ac value1="bye".

I try the following: divElement.findElement(By.xpath("/ancestor-or-self::*[@value1]"));but this will not work.

+3
source share
2 answers

Try a relative XPath expression, i.e. starting with ./not /:

divElement.findElement(By.xpath("./ancestor-or-self::*[@value1][1]"));
+3
source

You looked at this answer here . I believe you need

WebElement element = driver.findElement(By.xpath("//div[@id='2']/preceding::*[@value1][1]"));

, , . ?

-1

All Articles