Selecting an Element from the Parent

Prev Next

When selecting an element that may contain the changing IDs and class names, or the same values as other elements, it's best to specify properites of a parent element that are not likely to change or be duplicated.

Consider a scenario where you need to select the check box for "San Diego Padres at San Francisco Giants Tickets (Fan Appreciation Day)" at different times of the month. However, the event can be moved up or down in the list depending on the number of ticket types available (inventory), and this would change how this check box can be identified/addressed.
 

***The code for the last event would look something like this:

<tr deliveryoptions="1040" venueid="470634">
    <td><input id="selected_17" name="selected_17" type="checkbox"></td>
    <td>San Diego Padres at San Francisco Giants Tickets (Fan Appreciation Day)</td>
</tr>

The xpath for the checkbox next to "Fan Appreciation Day" is:  //*[@id='selected_17']

This xpath works as long as the event is in this row. However, if the event is moved up or down, this xpath would no longer identify this checkbox. To avoid this issue, you need to select an element which will not change.

The XPath for label containing "San Diego Padres at San Francisco Giants Tickets (Fan Appreciation Day)" is: //td[@class='event'][contains(text(),'Fan Appreciation Day')]

Selecting this text label will not check on the box. You must click on the checkbox next to the event. The XPath for this is: /td/input[@type='checkbox']

Notice the checkbox is located before the event so the checkbox is the parent element.

To specify the XPath for the checkbox that is next to that specific label at any given time, select the parent element by putting two periods “..” where an element would normally go. The element to the left of the double period will have its parent selected:

click(//td[@class='event'][contains(text(),'Fan Appreciation Day')]/../td/input[@type='checkbox'])

This xpath will always select the checkbox next to the label that contains "Fan Appreciation Day", regardless of where it appears in the list.