ABSOLUTE · RELATIVE · ATTRIBUTES · FUNCTIONS · AXES · CSS SELECTOR · TIPS & TRICKS · INTERVIEW READY
// XPath Syntax
Axis::NodeName[@Attribute='Value']
// Examples
// 1. Tag + Attribute
//input[@id='username']
// 2. Tag + Text
//button[text()='Login']
// 3. Any tag with attribute
//*[@placeholder='Enter email']
| Absolute XPath | Relative XPath | |
|---|---|---|
| Starts with | /html/body/... | //tagname |
| Starting point | Root of document | Anywhere in DOM |
| Fragile? | YES — breaks easily | NO — robust |
| Recommended? | ❌ Never use | ✅ Always use |
| Speed | Slow | Fast |
// ❌ Absolute — NEVER USE (brittle!)
/html/body/div[1]/form/div/input[2]
// ✅ Relative — ALWAYS USE
//input[@id='username']
//button[@type='submit']
//div[@class='login-form']//input
// Single element
WebElement el = driver.findElement(
By.xpath("//input[@id='username']"));
// Multiple elements
List<WebElement> els = driver.findElements(
By.xpath("//ul[@class='menu']/li"));
// By id
//input[@id='username']
// By name
//input[@name='email']
// By class
//button[@class='btn-primary']
// By type
//input[@type='submit']
// By placeholder
//input[@placeholder='Enter phone']
// By href
//a[@href='https://example.com']
// By value
//input[@value='Submit']
// By disabled attribute
//input[@disabled]
// By data-* attribute
//div[@data-id='123']
//button[@data-testid='login-btn']
// Any tag with attribute
//*[@id='submit']
//*[@class='active']
// Exact text match
//button[text()='Login']
//a[text()='Click Here']
//h1[text()='Welcome']
// Using normalize-space (handles spaces)
//button[normalize-space()='Log In']
// Text with contains()
//button[contains(text(),'Log')]
//a[contains(text(),'Click')]
//*[contains(text(),'Submit')]
// starts-with text
//p[starts-with(text(),'Welcome')]
// Case-sensitive — exact case needed!
// 'login' ≠ 'Login' ≠ 'LOGIN'
// Partial text in any tag
//*[contains(text(),'error')]
// Label text
//label[text()='User Name']
// Syntax: contains(@attr, 'value')
// Syntax: contains(text(), 'value')
// Attribute contains value
//input[contains(@id,'user')]
//div[contains(@class,'active')]
//a[contains(@href,'login')]
//input[contains(@placeholder,'email')]
// Text contains value
//button[contains(text(),'Login')]
//span[contains(text(),'Error')]
// Multiple classes (very common!)
//div[contains(@class,'btn') and
contains(@class,'primary')]
// Real world example
// Find: <input id="user_name_field">
//input[contains(@id,'user')]
// Syntax: starts-with(@attr, 'value')
// ID starts with
//input[starts-with(@id,'user')]
//div[starts-with(@class,'btn')]
// href starts with
//a[starts-with(@href,'https')]
// Text starts with
//p[starts-with(text(),'Welcome')]
//h2[starts-with(text(),'Error')]
// Dynamic IDs — very useful!
// Find: <td id="row_1_col_3">
//td[starts-with(@id,'row_')]
// AND — both conditions must be true
//input[@type='text' and @name='q']
//button[@type='submit' and
contains(@class,'primary')]
//*[@id='x' and contains(text(),'OK')]
// OR — either condition can be true
//input[@id='email' or @id='phone']
//button[text()='OK' or
text()='Confirm']
// NOT — negate a condition
//input[not(@disabled)]
//div[not(contains(@class,'hidden'))]
// Combined AND + OR
//input[(@type='text' or @type='email')
and @required]
// By position — index starts at 1!
// Get 2nd row in table
//table/tbody/tr[2]
// Shorthand for position()
//ul/li[position()=1] ← first item
//ul/li[position()=2] ← second item
// last() — get last element
//ul/li[last()]
//tr[last()]/td[1]
// last()-1 = second to last
//ul/li[last()-1]
// count() — count child elements
//ul[count(li)=5] ← ul with 5 li items
// Multiple elements with index
// 3rd input on page
(//input[@type='text'])[3]
(//button)[1] ← first button
(//a)[last()] ← last anchor tag
// normalize-space — trims whitespace
// Handles: " Login " = "Login"
//button[normalize-space()='Login']
//td[normalize-space()='John Doe']
// normalize-space with text()
//*[normalize-space(text())='Submit']
// string-length — check text length
//input[string-length(@value)>0]
//p[string-length(text())>10]
// translate() — case-insensitive match
//button[translate(text(),
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz')
='login']
// substring() — part of string
//*[substring(@id,1,4)='user']
// Gets first 4 chars of @id
// Combine class + type + name
//input[@type='text' and
@class='form-control']
// Attribute + text combo
//a[@class='nav-link' and
text()='Home']
// Data attributes
//button[@data-testid='submit']
//div[@data-role='dialog']
// Aria attributes (accessibility)
//button[@aria-label='Close']
//div[@role='alert']
//input[@aria-required='true']
// Dynamic ID patterns
// e.g. id="user_1234_field"
//input[contains(@id,'user') and
contains(@id,'field')]
// Auto-generated classes
// e.g. class="btn btn-primary btn-lg"
//button[contains(@class,'btn-primary')]
// Timestamp-based IDs
// e.g. id="modal_1709123456"
//div[starts-with(@id,'modal_')]
// React/Angular generated IDs
//*[contains(@id,'react-select')]
//*[contains(@class,'ng-')]
// Using visible text (most stable)
//button[contains(text(),'Submit')]
//td[contains(text(),'John')]
| Operator | Meaning | Example |
|---|---|---|
| = | Equal to | @id='name' |
| != | Not equal | @type!='hidden' |
| < | Less than | @count<5 |
| > | Greater than | @size>10 |
| and | Both true | @a='x' and @b='y' |
| or | Either true | @a='x' or @a='y' |
| not() | Negate | not(@disabled) |
| | | Union (both) | //a | //button |
| Axis | What it selects |
|---|---|
| parent | Direct parent node |
| child | Direct children only |
| following-sibling | Siblings AFTER current node |
| preceding-sibling | Siblings BEFORE current node |
| ancestor | All ancestors up to root |
| descendant | All children, grandchildren |
| following | All nodes after in document |
| preceding | All nodes before in document |
| self | Current node itself |
| ancestor-or-self | Self + all ancestors |
| descendant-or-self | Self + all descendants |
// parent:: — go UP to parent
// Find parent div of an input
//input[@id='email']/parent::div
// Find label's parent form
//label[text()='Email']/parent::form
// Any parent tag
//input[@id='un']/parent::*
// child:: — go DOWN to children
// Find direct li children
//ul[@class='menu']/child::li
// Same as / shorthand
//ul[@class='menu']/li ← same thing
// Find all child inputs in form
//form[@id='login']/child::input
// ancestor:: — any ancestor going UP
// Find table ancestor of a cell
//td[text()='John']/ancestor::table
// Find form ancestor of button
//button[@type='submit']/ancestor::form
// ancestor-or-self
//input/ancestor-or-self::div
// Self axis
//input[@id='x']/self::input
// following-sibling — after current node
// MOST COMMON USE CASE:
// Find input next to a label
// HTML: <label>Email</label><input...>
//label[text()='Email']/
following-sibling::input
// Find button next to error span
//span[text()='Error']/
following-sibling::button
// Find td next to "Name" td
//td[text()='Name']/
following-sibling::td
// First following sibling
//label[text()='Phone']/
following-sibling::input[1]
// Any following sibling
//li[1]/following-sibling::li
// preceding-sibling — before current node
// Find label before input
//input[@id='email']/
preceding-sibling::label
// Find td before a specific cell
//td[text()='100']/
preceding-sibling::td[1]
// Gets the td immediately before
// Find heading before a list
//ul[@class='items']/
preceding-sibling::h2
// descendant:: — any level below
// All inputs inside a div
//div[@id='form']/
descendant::input
// Same as // shorthand
//div[@id='form']//input ← same!
// All buttons anywhere in section
//section[@class='main']/
descendant::button
// following:: — all nodes after
// (different from following-sibling)
// Includes nested children too
//h1[text()='Login']/
following::input
// Gets ALL inputs anywhere after h1
// preceding:: — all nodes before
//button[@id='submit']/
preceding::input
// SCENARIO 1:
// Click Edit for row with "John"
// HTML: <td>John</td><td><button>Edit</button></td>
//td[text()='John']/
following-sibling::td/
button[text()='Edit']
// SCENARIO 2:
// Find input by label name
// HTML: <label>Mobile</label><input>
//label[contains(text(),'Mobile')]/
following-sibling::input
// SCENARIO 3:
// Delete button in specific table row
//tr[td[text()='Alice']]/
descendant::button[text()='Delete']
// By ID — prefix: #
By.cssSelector("#username")
// Finds: <input id="username">
// By Class — prefix: .
By.cssSelector(".btn-submit")
// Finds: <button class="btn-submit">
// By Tag name
By.cssSelector("input")
// By Tag + ID
By.cssSelector("input#email")
// By Tag + Class
By.cssSelector("button.btn-primary")
// Multiple classes
By.cssSelector(".btn.btn-lg.active")
// Tag + ID + Class
By.cssSelector("input#email.form-ctrl")
// Exact attribute value
By.cssSelector("input[type='email']")
By.cssSelector("a[target='_blank']")
// Attribute exists (any value)
By.cssSelector("input[required]")
By.cssSelector("input[disabled]")
// Contains: *=
By.cssSelector("input[id*='user']")
By.cssSelector("a[href*='login']")
// Starts with: ^=
By.cssSelector("input[id^='user']")
By.cssSelector("a[href^='https']")
// Ends with: $=
By.cssSelector("input[id$='field']")
By.cssSelector("img[src$='.png']")
// Word match: ~=
By.cssSelector("div[class~='active']")
// Direct child: >
By.cssSelector("form > input")
// Only direct input children of form
// Any descendant: space
By.cssSelector("form input")
// All inputs anywhere inside form
// Adjacent sibling: +
By.cssSelector("label + input")
// Input immediately after a label
// General sibling: ~
By.cssSelector("label ~ input")
// All inputs that are siblings of label
// Deep nested
By.cssSelector("div.form > div > input")
By.cssSelector("table tbody tr td a")
// :nth-child — 1-based index
By.cssSelector("ul li:nth-child(1)")
By.cssSelector("tr:nth-child(3) td")
// :first-child / :last-child
By.cssSelector("li:first-child")
By.cssSelector("tr:last-child")
// :nth-of-type
By.cssSelector("p:nth-of-type(2)")
// :not() — exclude elements
By.cssSelector("input:not([disabled])")
By.cssSelector("li:not(.active)")
// :checked (checkbox/radio)
By.cssSelector("input:checked")
// :enabled / :disabled
By.cssSelector("input:enabled")
By.cssSelector("button:disabled")
| Feature | XPath | CSS Selector |
|---|---|---|
| Direction | Both ways (up & down) | Down only |
| Text search | ✅ text() | ❌ Not supported |
| Axes | ✅ parent, sibling | Limited |
| Speed | Slower | Faster |
| Syntax | Complex | Simpler |
| Browser support | All | All |
| Contains | contains() | *= |
| Starts-with | starts-with() | ^= |
| Ends-with | No (use substring) | $= |
| nth element | [position()=n] | :nth-child(n) |
// Test XPath in browser console
$x("//input[@id='username']")
$x("//button[text()='Login']")
$x("//div[contains(@class,'active')]")
// Test CSS in browser console
$$("input#email")
$$("button.btn-primary")
$$("input[type='text']")
// Check count of elements
$x("//li").length
$$("li").length
| Priority | Locator | Use When |
|---|---|---|
| 1st | By.id() | Element has unique ID |
| 2nd | By.name() | Element has name attr |
| 3rd | By.cssSelector() | No text search needed |
| 4th | By.xpath() | Need text / axes |
| 5th | By.className() | Unique single class |
| Last | By.tagName() | Only one of that tag |