sourabh
sourabh

Reputation: 11

xpath preceding-sibling correctly

<table width="100%" cellpadding="2" border="0" cellspacing="0">
 <tbody>
   <tr>
    <tr>
     <td valign="top" align="left" style="width:2%">
       <input id="ucRightAdd_grdList_ctl04_chkSelect" type="checkbox"    name="ucRightAdd$grdList$ctl04$chkSelect">
     </td>
     <td width="65%" valign="top">
       <span class="BodyText"> Workflow View </span>
     </td>

In above html code I need to check the checkbox corresponding to text Workflow View. I used following code for that but its not working:

Driver.findElement(By.xpath("//span[contains(., \"" +rightName+ "\")]../preceding-sibling::/td/input[@type='checkbox']")).click();

Upvotes: 0

Views: 20593

Answers (4)

user19660488
user19660488

Reputation: 1

Here I have used the sibling concept.

First taken the parent tag and then traversing to the siblings

//input[@id='ucRightAdd_grdList_ctl04_chkSelect']//parent::td[@valign='top']//forward-sibling::td[@valing='top']//span

Upvotes: 0

chris-crush-code
chris-crush-code

Reputation: 1149

This is old but I think your problem is with the slash after the preceding-sibling axis. Per W3Schools you need a node test after the double colon: axisname::nodetest[predicate]

So instead of:

Driver.findElement(By.xpath("//span[contains(., \"" +rightName+ "\")]../preceding-sibling::/td/input[@type='checkbox']")).click();

Do this:

Driver.findElement(By.xpath("//span[contains(., \"" +rightName+ "\")]../preceding-sibling::td/input[@type='checkbox']")).click();

Upvotes: 0

Bartosz Drzewinski
Bartosz Drzewinski

Reputation: 16

If you have one input per row, you could use following simple xpath:

//tr[normalize-space(.)='Workflow View']/td/input

Upvotes: 0

unutbu
unutbu

Reputation: 880707

You could use the XPath

//span[contains(text(), "Workflow View")]/../preceding-sibling::td/input[@type="checkbox"]

Note that

  • use text() in contains(text(), "Workflow View") to obtain the text inside the span tag.
  • there should be a forward-slash after [contains(text(), "Workflow View")]
  • there should not be a forward-slash between preceding-sibling:: and td.

Alternatively, you might also consider using

//span[contains(text(), "Workflow View")]/preceding::input[@type="checkbox"]

which is a little simpler, but which also has a different meaning. The preceding axis traverses all tags before the current node excluding ancestors:

>>> doc.xpath('//span[contains(text(), "Workflow View")]/preceding::*')
[<Element tr at 0x7ff01f819f18>,
 <Element td at 0x7ff01f819e68>,
 <InputElement 7ff01f819f70 name='ucRightAdd$grdList$ctl04$chkSelect' type='checkbox'>]

Upvotes: 2

Related Questions