🏠Quick Reference for XPath + CSS

What are the different approaches to using XPath and CSS Selector?

DescriptionXPathCSS Selector

Whole WebPage

/html

html

Whole WebPage body

/html/body

body

Image element

//img

img

Link

//a[@href = 'url']

a[href = 'url']

Direct Child

//div/a

div > a

Id

//tagName[@id=’idValue’]

tagName#idValue

Class

//tagName[@class=’classValue’]

tagName.Value of Class attribute

Attribute

//tagname[@attribute-name=’value1′]

tagName[attribute=Value of attribute]

Multiple Attributes

//input[@type='submit' and @name='btnLogin']

tagname[attribute1='value1'][attribute2='value2']

Contains

//*[contains(@type,'sub')]

tagname[attribute*=substring]

Starts with

//tagname[starts-with(@attribute, ‘Start value’)]

tagname[attribute^=prefix of the String]

Ends with

//tagname[ends-with(@attribute, ‘End value’)]

tagname[attribute$=suffix of the String]

Matches

//*[matches(@type,'value')]

N/A

First Child

//ul[@id=’list’]/li[1]

ul#list li:first-child

Last Child

//ul[@id=’list’]/li[last()]

ul#list li:last-child

nth Child

//ul[@id=’list’]/li[3]

ul#list li:nth-child(3)

Text Value

//td[text()=‘textname']

N/A

Element preceding some sibling

E2/preceding-sibling::E1

N/A

Sibling element immediately preceding

E/preceding-sibling::*[1]

N/A

User interface element that is disabled

E[@disabled]

E:disabled

Checkbox (or radio button) that is checked

//*[@checked]

*:checked

Text Value

//td[text()=‘textname']

N/A

What are the differences between XPath and CSS locators?

Traversal:

❎ XPath allows bidirectional traversal.

//div[@id='id']//preceding::input
//div[@id='id']//following::input

➡️ CSS only moves forward.

 div#id ~ input

👉 So XPath has more powerful traversal.

Performance:

✅ CSS selectors are faster since browsers optimize CSS.

Readability:

✅ CSS locators are more concise and readable.

input[type='text']
//input[@type='text']

Last updated