Viorel Casapu
Viorel Casapu

Reputation: 229

in selenium find the following sibling of an element with a specific child css selector

I have a tree like this:

<table>
<tbody>
<tr>
 <td>
  <span>MySpan1</span>
 </td>
<tr>
<tr>
 <td>
 </td>
 <td>
  <div>
   <a title="my_title1"></a>
  </div>
 <td>
</tr>

<tr>
 <td>
  <span>MySpan2</span>
 </td>
<tr>
<tr>
 <td>
 </td>
 <td>
  <div>
   <a title="my_title2"></a>
  </div>
 <td>
</tr>
</tbody>
</table>

I need to select <a title="my_title2"></a> knowing that its tr parent must have a sibling tr/td/span[contains(text(),'MySpan2')]
If it is not possible with css selector, then can it be achieved with xpath?

Upvotes: 2

Views: 2515

Answers (2)

cruisepandey
cruisepandey

Reputation: 29382

Please use this xpath

//span[contains(text(),'MySpan2')]/ancestor::tr/following-sibling::tr[2]/descendant::a[@title='my_title2']

we are targeting MySpan2 span then go to ancestor which is tr then we have to go to it's second following-sibling and then target a tag with title my_title2

You cannot use css selector for this, xpath is only choice.

We are traversing upward in HTMLDOM so css has to be ruled out.

Please refer xpath axes

Update :

Irrespective of tr sibling number :

//span[contains(text(),'MySpan2')]/ancestor::tr/following-sibling::tr/descendant::a[@title='my_title2']

Upvotes: 2

Viorel Casapu
Viorel Casapu

Reputation: 229

This is what worked for me:
//span[contains(text(),'MySpan2')]/ancestor::tr/following-sibling::tr/td/div/a[@title='my_title2']

Upvotes: 1

Related Questions