Or Smith
Or Smith

Reputation: 3616

Xpath / Getting the most close ancestor with some value

I want to get the most close ancestor of a WebElement with some attribute.

For example:

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

I have a WebElment in Jave that presents the div (id="2")

How I can get the most close parent which have the value1 attribute?

In this case, I would get the element a with value1="bye".

I try the next: divElement.findElement(By.xpath("/ancestor-or-self::*[@value1]")); but this doesn't work.

Upvotes: 3

Views: 1626

Answers (2)

nilesh
nilesh

Reputation: 14287

Did you take a look at this answer here. I believe thats what you need

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

That said, I am not sure why you have a need to do this. Can you elaborate more?

Upvotes: -1

paul trmbrth
paul trmbrth

Reputation: 20748

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

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

Upvotes: 4

Related Questions