Dynamic XPath
Master dynamic XPath techniques for elements whose attributes, text or positions change during execution.
What You Will Practice
- Identify dynamic attributes.
- Use XPath contains().
- Use XPath starts-with().
- Locate elements by text().
- Use normalize-space().
- Combine conditions using and / or.
- Navigate parent and child elements.
- Practice XPath axes.
contains()
Locate an element when only part of an attribute value is stable.
//button[contains(@id,'dynamicLoginButton')]
starts-with()
Locate an element when its attribute begins with a known value.
//input[starts-with(@id,'userField_')]
text()
Locate an element using its visible text.
//button[text()='Edit Employee']
normalize-space()
Handle unwanted spaces around element text.
//button[normalize-space()='Submit Form']
and / or Conditions
Combine multiple XPath conditions to create more reliable locators.
//input[contains(@id,'employeeEmail') and @type='email']
//input[@type='email' or @type='password']
Parent & Child
Navigate from a parent element to its child element.
//div[@id='employeeCard']//button
XPath Axes
Practice following-sibling, preceding-sibling and ancestor.
//span[text()='Employee Name']/following-sibling::strong
//strong[@id='axisEmployeeName']/ancestor::div[@class='axis-row']
Dynamic Employee Table
Use dynamic XPath to locate an action belonging to a specific employee.
//div[contains(@class,'dynamic-table-row')][.//span[text()='Arjun Kumar']]//button
Dynamic XPath Cheat Sheet
//button[
contains(
@id,
'login'
)
]
//input[
starts-with(
@id,
'user_'
)
]
//button[
text()='Login'
]
//button[
normalize-space()
='Submit'
]
//div[@id='card']
//button
//span[
text()='Name'
]
/following-sibling::strong