Selenium get ancestor element with xpath

  • 1 Replies
  • 1199 Views
*

Ali

  • *
  • 8
Selenium get ancestor element with xpath
« on: June 21, 2016, 18:34:56 pm »
I have the following HTML:

Code
<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)

Re: Selenium get ancestor element with xpath
« Reply #1 on: June 27, 2016, 19:20:45 pm »
It would be a lot easier to select the ancestor first and check if it has a descendant with that attribute

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

 

Sitemap 1 2 3 4 5 6 7 8