Jrawr
Jrawr

Reputation: 199

Selenium verify if an element is a child of another in Java

I have a series of nested elements in a page that I'm trying to navigate. The html below is a simplified version:

<div>
  <h1 id="This is an id">The header is an identifier</h1>
  <table>
      <tr></tr>
      <tr>
         <ul>
           <li>
             <a>
               <span>This my target</span>
  </table>
</div>
        
        <h1>Also text</h1>
        <a>
        <span>This target has the same text<span>
         

The structure of the top div can very dramatically. I am trying to find an elements using xpath and text contains. However, I am having trouble verifying that the target is indeed the one inside the proper div. If there a way to scale back up the dom tree somehow if I don't know the exact layout of it every time?

Upvotes: 0

Views: 647

Answers (2)

user8195234
user8195234

Reputation:

You can try using > operation with CSS selector.

Example: to access "This my target", you use driver.findElement(By.cssSelector("li>a>span"));

Upvotes: 1

lauda
lauda

Reputation: 4173

For checking an text inside a div you could compose an path like:

//div//*[contains(text(), 'my text')]

If you need to check inside a specific div then you should identify the div first.

For example if the div has an attribute like class="my_class" then use:

//div[@class='my_class']//*[contains(text(), 'my text')]

You can find more path examples on w3schools xpath syntax

Upvotes: 0

Related Questions