</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How can we locate an element by only partially matching its attribute value in XPath?

Use contains() function in XPath to partially match dynamic attribute values.

Answer

Use the contains() function in XPath to partially match attribute values. This is especially useful for elements with dynamic IDs or class names.

Syntax:

XPATH
//*[contains(@attributeName, ''partialValue'')]

Examples:

XPATH
//*[contains(@id, ''user'')]
//button[contains(@class, ''btn'')]
//a[contains(text(), ''Login'')]
//input[contains(@name, ''search'')]

Other partial matching functions:

FunctionDescriptionExample
contains()Value contains substringcontains(@id,''user'')
starts-with()Value starts withstarts-with(@id,''user'')
normalize-space()Ignore extra spacesnormalize-space(text())=''Login''

Real-world use case: Dynamic IDs like username_12345 or username_67890 → use contains(@id, ''username'')

Follow AutomateQA

Related Topics