bagelmakers
bagelmakers

Reputation: 409

Using xpath to select an element based on its grandchildren

I am trying to find an element in a webpage based on the child of the child of the element I want. I need this because it is the clickable part of the webpage.

<table id="uniqueId">
  <tbody>
    <tr></tr>
    <tr class="row" onclick="do_a_thing">
      <td>
        <input type="hidden" value="1" />
      </td>
      <td>
        <input type="hidden" value="1" />
      </td>
    </tr>
    <tr class="row" onclick="do_a_thing">
      <td>
        <input type="hidden" value="2" />
      </td>
      <td>
        <input type="hidden" value="1" />
      </td>
    </tr>
    <tr class="row" onclick="do_a_thing">
      <td>
        <input type="hidden" value="3" />
      </td>
      <td>
        <input type="hidden" value="1" />
      </td>
    </tr>
  </tbody>
</table>

I currently have the following xpath to select the table row that contains the attribute where an input has value = 2:

//*table[@id='uniqueId']//tr[td[0]/value='2']

According to a previous question, this should work. Why doesn't it work here?

Upvotes: 0

Views: 2058

Answers (1)

matthias_h
matthias_h

Reputation: 11416

The following XPath

//table[@id='uniqueId']//tr[td/input[@value='2']]

when applied to your input HTML has the output

<tr class="row" onclick="do_a_thing">
  <td>
    <input type="hidden" value="2" />
  </td>
  <td>
    <input type="hidden" value="1" />
  </td>
</tr>

The XPath tr[td[0]/value='2'] won't work as the value attribute with the value 2 belongs to the input which is in the td:

tr[td/input[@value='2']]

and in addition, as mentioned by LarsH as comment, td[0] meaning td[position() = 0] won't select any element as position() is 1-based, so [0] is a predicate that is always false.

Upvotes: 2

Related Questions