Often I find myself using certain XPath patterns and then forgetting how to do it, so I decided to create XPath cheatsheet.

1. XPath to search by partial id, so let say you have div id which includes the word “test”:

html:

<div id="mytest"></div>

xpath:

//div[contains(@id,'test')]

2. Select element with specific text

html:

<div id="mytest">Some text here</div>

xpath:

//div[text() = 'Some text here']

3. Get parent element

html:

<td>
   <a>Your first link text</a>
</td>
<td>
   <a>Your second link text</a>
</td>

xpath:

//a[text()='Your first link text']/parent::td

4. Get first found element

html:

<div data-qa="my-data-qa"></div>
<div data-qa="my-data-qa"></div>
<div data-qa="my-data-qa"></div>

xpath:

//div[contains(@data-qa, "my-data-qa"))[0]

5. Get element starts-with

html:

<div data-qa="my-data-qa-1"></div>
<div data-qa="my-data-qa-2"></div>
<div data-qa="my-data-qa-3"></div>

xpath:

//div[starts-with(@data-qa,'my-data-')]

6. Get element ends-with

html

<div data-qa="1-my-data-qa"></div>
<div data-qa="2-my-data-qa"></div>
<div data-qa="3-my-data-qa"></div>

xpath

//div[ends-with(@data-qa,'-my-data-qa')]

6. Pass number to xpath, in the example below I’m passing a number of a row in a table

xpath:

//tbody/tr[" + number + "]

7. Pass text to xpath, similar to passing a number:

xpath:

//div[text()='" + text + "']

8. Find element with specific class or id

xpath:

//i[@class='icon-edit']

9. Select with specific class and not having another class

xpath:

//div[@class='flyout' and not(@class='flyout-hidden')]

10. Get last element in the dom

xpath:

div[2]//div[last()]

11. Select element with specific value

xpath:

//select[@id='status']/option[@value='S']

12. Select element with specific class and text

xpath:

//span[@class='ui-button-text' and contains(text() ,'Yes')]

Feel free add your snippets to comment section and I will add it to the blog post.

13. Select first element in DOM:

(//a[text() = 'Some_Text'])[1]