Locating Web Elements by walking up the DOM

1 vote

This is one of the rare cases where we need use XPath, as parent selecting is not supported in CSS. We prepared a sample to visualize this case. Take a look on the following website: when to use XPath

As you can see the amount of unique identifiers is very limited. However, we can select the `edit` or `delete` button based on the value which is present in the first table-cell.

The following example will select the `edit` button of the third row.

//td[contains(text(), '678')]/../td/button[@class = 'edit']

As you can see, we first select the right table-cell based on the text it contains. Then we go one level up ( ../) in the HTML structure and select the right button based on the `class`.

 

Examine your knowledge and play the ‘locator game‘.

Locating Web Elements by index matching

0 votes

Probably this is not the best way of locating elements, but sometimes it’s needed to use these kind of locator strategy. A reason might be the lack of element identifiers.

CSS XPath
Select second element E:nth-child(2) //E[2]
First <E> child E:first-of-type //E[1]
Last <E> child E:last-of-type //E[last()]

 

Examine your knowledge and play the ‘locator game‘.

Locating Web Elements by label matching

0 votes

Not always you want to take a look at the underlying HTML code. Therefore it can be handy to define the text of the label in front of form fields. The following example defines the use of label matching.

Example HTML:

<label for="lastname">Last Name</label>
<input type="text" id="lastname" />

We can use:

`//label[contains(text(), 'Last Name')]/../input`

It can be a bit tricky as the label can be defined before, after or around the form fields.

 

Examine your knowledge and play the ‘locator game‘.

Locating Web Elements by text matching

1 vote

Although it is not the best solution, sometimes we need to locate elements based on the text displayed. It’s not the best solution if you have to test a multilingual website, because the text is different in every language.

Using XPath we have the following options:

Text equals

//E[text() = 'Displayed text']

Text contains

//E[contains(text(), 'Displayed text')]

 

Examine your knowledge and play the ‘locator game‘.