TestProject Forum
Powered by leading experts in the test automation community

Selenium get ancestor element with xpath

I have the following HTML:

<div id="container">
  <div>
       <table>
              <tbody>
                         <td> 
                              <p id="rl-text"> 
                         </td>
              <tbody>
       </table>
  </div>
</div>

I want to get the div element with ‘container’ id from the paragraph with ‘rl-text’
Usually what I do is go up with xpath a few times: driver.findElement(by.xpath(’…’));
But I have to guess the amount of times to go up.
I’m looking for a more generic approach for an xpath to get the top element div (container)

It would be a lot easier to select the ancestor first and check if it has a descendant with that attribute

driver.findElement(by.xpath('.//div[contains(@class, 'container')][.//p[@id="rl-text"]]'));