user3346145
user3346145

Reputation: 37

java-selenium xpath to find preceding node

I have below code

<div>
<tr class="clickable-row" _ngcontent-c2="">
.
.
.
<tr class="clickable-row" _ngcontent-c2="">
   <td _ngcontent-c2="">
     <input type="checkbox" _ngcontent-c2="" value="">
   </td>
   <td _ngcontent-c2=""> 
      View only 
   </td>
</tr>
<div>

Now I want to click on the check box near the 'View only ' text. I tried

 //input[@type='checkbox']/following::td[contains(text(),'View only')]

but it clicks on the text not the check box. Any help would be appreciated

Upvotes: 1

Views: 104

Answers (2)

M3rr1
M3rr1

Reputation: 159

Another way you can traverse up in xpath by adding .. to the part where you want to go up. To do so, you need to grab the child element before you go up.

I am assuming you want to click the checkbox that is one level above the 'View only' text, and that the text + checkbox combination is unique (there is no other 'View only' text with a checkbox above it in the same page); in that case the xpath you want is

//td[contains(text(), 'View only')]/../td/input`.

This xpath goes to the td that contains 'View only', goes up one level to the tr, then to the first td and to the input.

If you want a simpler match for the text you can do td[normalize-space()='View only']; if you want to be more specific after the /../ and tell to grab the first td you can put td[1], and you can also add the [@type='checkbox'] to the input to ensure you grab the one that is a checkbox.

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193088

To click on the checkbox near the 'View only' text you can use the following xpath :

//tr[@type='clickable-row']//td[normalize-space()='View only']//preceding::td[1]/input[@type='checkbox']

Upvotes: 1

Related Questions