Popular Searches
Popular Course Categories
Popular Courses

Relative XPath

XPath in Selenium

Relative XPath in Selenium

Relative XPath is an XPath expression used in Selenium WebDriver to locate web elements without specifying the complete path from the root of the HTML document. Instead of following every level of the DOM hierarchy, Relative XPath starts from a particular point and identifies the required element using tag names, attributes, text, indexes, relationships, or other XPath functions.

Relative XPath is commonly used for locating web elements such as input fields, buttons, links, checkboxes, dropdowns, forms, tables, and dynamically generated elements. Selenium training at JustAcademy includes locators such as XPath and CSS selectors as part of Selenium WebDriver and web-element automation. JustAcademy Selenium Training Course

You can also visit the Selenium Course Demo Registration page for course-demo information.


1. What is Relative XPath?

Relative XPath is an XPath expression that locates an element from a specific point in the DOM instead of starting from the root of the HTML document.

The most common Relative XPath syntax starts with double forward slashes:

//tagname

For example:

//input

This expression searches for input elements in the document without specifying the complete HTML hierarchy.


2. Basic Syntax of Relative XPath

The general syntax of Relative XPath is:

//tagname

Relative XPath can also use attributes:

//tagname[@attribute='value']

Example:

//input[@id='username']

This XPath searches for an input element whose ID attribute is username.


3. Why is Relative XPath Used in Selenium?

Relative XPath provides a flexible way to locate web elements without depending on the complete DOM hierarchy.

It can be used to:

  • Locate elements using attributes.
  • Locate elements using visible text.
  • Locate elements using partial attribute values.
  • Locate elements using indexes.
  • Navigate between parent and child elements.
  • Navigate between sibling elements.
  • Locate dynamically generated elements.
  • Work with deeply nested elements.
  • Reduce dependency on the complete HTML structure.
  • Create reusable Selenium locators.


4. Absolute XPath vs Relative XPath

Absolute XPath follows the complete path from the root of the HTML document.

/html/body/div/form/input

Relative XPath identifies the element without specifying the complete path.

//input

A more specific Relative XPath can be:

//input[@id='username']


5. Relative XPath Starts with Double Slash

Relative XPath commonly starts with two forward slashes.

//input

//button

//a

//div

//form

The double slash allows XPath to search for matching elements anywhere in the document relative to the current context.


6. Relative XPath Using Tag Name

The simplest Relative XPath uses only the tag name.

//input

This searches for input elements.

Other examples:

//button

//a

//div

//form

//table

//tr

//td

When many elements have the same tag name, additional conditions should be used to identify the required element.


7. Relative XPath Using ID Attribute

An ID is one of the most commonly used attributes with Relative XPath.

Consider:

<input id="username" type="text">

The Relative XPath is:

//input[@id='username']

Selenium example:

driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin");


8. Relative XPath Using Name Attribute

The name attribute can also be used to identify an element.

<input type="text" name="username">

XPath:

//input[@name='username']

Selenium:

driver.findElement(By.xpath("//input[@name='username']")).sendKeys("admin");


9. Relative XPath Using Class Attribute

The class attribute can be used to locate an element.

<input class="login-input" type="text">

XPath:

//input[@class='login-input']

Selenium:

driver.findElement(By.xpath("//input[@class='login-input']")).sendKeys("admin");

When an element contains multiple classes, exact class matching may not always be suitable. In such cases, contains() can be useful.


10. Relative XPath Using Multiple Attributes

Multiple attributes can be combined when one attribute is not sufficient to identify an element uniquely.

HTML:

<input id="username" name="user" type="text">

XPath:

//input[@id='username' and @name='user']

Selenium:

driver.findElement(

    By.xpath("//input[@id='username' and @name='user']")

);


11. Relative XPath Using the AND Operator

The and operator is used when multiple conditions must be true.

//input[@type='text' and @name='username']

This XPath searches for an input element where both conditions are satisfied.


12. Relative XPath Using the OR Operator

The or operator can be used when either of the conditions can identify the element.

//input[@id='username' or @name='username']

This XPath matches an input where either the ID or name matches username.


13. Relative XPath Using Text

The text() function can locate an element based on its visible text.

HTML:

<button>Login</button>

XPath:

//button[text()='Login']

Selenium:

driver.findElement(By.xpath("//button[text()='Login']")).click();


14. Relative XPath Using Partial Text

The contains() function can be used when only part of the visible text is known.

HTML:

<button>Login to Application</button>

XPath:

//button[contains(text(),'Login')]

This can match a button containing the word Login.


15. Relative XPath Using contains()

The contains() function is useful when an attribute value is dynamic or only part of the value is stable.

HTML:

<input id="user_12345" type="text">

XPath:

//input[contains(@id,'user_')]

This XPath searches for an input whose ID contains user_.


16. Relative XPath Using starts-with()

The starts-with() function can identify elements whose attribute value starts with a specific string.

HTML:

<input id="username_12345" type="text">

XPath:

//input[starts-with(@id,'username_')]

This is useful when an application generates dynamic IDs with a stable prefix.


17. Relative XPath Using normalize-space()

The normalize-space() function removes leading and trailing whitespace and normalizes whitespace in text.

Example:

//button[normalize-space()='Login']

This can be useful when the visible text contains unnecessary spaces or formatting differences.


18. Relative XPath Using Index

Indexes can be used when multiple elements match the same XPath.

For example:

(//input)[1]

This selects the first input matching the expression.

(//input)[2]

This selects the second input.

Indexes should be used carefully because the position of elements can change when the DOM changes.


19. Relative XPath with Position()

The position() function can be used to identify an element at a particular position.

//input[position()=1]

Another example:

//input[position()=2]

This can be useful when working with multiple similar elements.


20. Relative XPath for Buttons

Consider:

<button id="loginBtn">Login</button>

Possible XPath expressions are:

//button[@id='loginBtn']

Or:

//button[text()='Login']

Or:

//button[contains(text(),'Login')]

Selenium example:

driver.findElement(By.xpath("//button[@id='loginBtn']")).click();


21. Relative XPath for Links

HTML:

<a href="/home">Home</a>

XPath using text:

//a[text()='Home']

XPath using href:

//a[@href='/home']

XPath using contains:

//a[contains(@href,'home')]


22. Relative XPath for Checkboxes

HTML:

<input type="checkbox" id="terms">

XPath:

//input[@id='terms']

Selenium:

driver.findElement(By.xpath("//input[@id='terms']")).click();


23. Relative XPath for Radio Buttons

HTML:

<input type="radio" name="gender" value="male">

XPath:

//input[@type='radio' and @value='male']

Selenium:

driver.findElement(

    By.xpath("//input[@type='radio' and @value='male']")

).click();


24. Relative XPath for Dropdown Elements

HTML:

<select id="country">

    <option>India</option>

    <option>USA</option>

</select>

Select element:

//select[@id='country']

Option:

//select[@id='country']/option[text()='India']


25. Relative XPath for Form Elements

Consider:

<form id="loginForm">

    <input name="username">

    <input name="password">

    <button>Login</button>

</form>

Username:

//form[@id='loginForm']//input[@name='username']

Password:

//form[@id='loginForm']//input[@name='password']

Login button:

//form[@id='loginForm']//button[text()='Login']


26. Relative XPath Using Parent

The parent axis can be used to move from an element to its parent.

HTML:

<div class="login">

    <input id="username">

</div>

XPath:

//input[@id='username']/parent::div

This XPath locates the div parent of the username input.


27. Relative XPath Using Child

The child relationship can be used to navigate from a parent element to a child element.

//div[@class='login']/child::input

A shorter equivalent form can be:

//div[@class='login']/input


28. Relative XPath Using Ancestor

The ancestor axis finds an element above the current element in the DOM hierarchy.

//input[@id='username']/ancestor::form

This locates the form ancestor of the username input.


29. Relative XPath Using Descendant

The descendant axis locates elements anywhere below the current element.

//form[@id='loginForm']/descendant::input

This finds input elements that are descendants of the login form.


30. Relative XPath Using Following-Sibling

The following-sibling axis locates sibling elements that appear after the current element.

HTML:

<div>

    <label>Username</label>

    <input type="text">

</div>

XPath:

//label[text()='Username']/following-sibling::input


31. Relative XPath Using Preceding-Sibling

The preceding-sibling axis locates sibling elements that appear before the current element.

//input[@id='username']/preceding-sibling::label

This can locate the label that appears before the username input.


32. Relative XPath Using Following

The following axis selects nodes that appear after the current node in the document.

//label[text()='Username']/following::input

This can locate input elements appearing after the username label.


33. Relative XPath Using Preceding

The preceding axis selects nodes that occur before the current node in the document.

//input[@id='password']/preceding::input

This can locate input elements appearing before the password input.


34. Relative XPath Using Descendant Relationship

The double slash can also be used to locate descendants without specifying every intermediate element.

//div[@id='login']//input

This searches for input elements anywhere inside the div with ID login.


35. Relative XPath with Multiple Conditions

Multiple conditions can be combined to create a more specific locator.

//input[@type='text' and @name='username' and @placeholder='Enter Username']

This XPath matches an input where all three conditions are satisfied.


36. Relative XPath with not()

The not() function can be used when a specific attribute value should be excluded.

//input[not(@disabled)]

This expression identifies input elements that do not have the disabled attribute.


37. Relative XPath Using Multiple Text Conditions

Multiple conditions can also be applied to visible text.

//button[contains(text(),'Login') and not(@disabled)]

This can identify a button containing Login that is not disabled.


38. Relative XPath for Dynamic IDs

Dynamic web applications sometimes generate changing ID values.

For example:

<input id="user_12345" type="text">

On another page load, it may become:

<input id="user_67890" type="text">

An XPath using contains() can focus on the stable part:

//input[contains(@id,'user_')]


39. Relative XPath for Dynamic Class Values

Dynamic applications may also generate changing class names.

<button class="btn-login-123">Login</button>

XPath:

//button[contains(@class,'btn-login')]

This focuses on the stable portion of the class value.


40. Relative XPath with normalize-space()

When text contains additional spaces, normalize-space() can make the XPath more reliable.

HTML:

<button> Login </button>

XPath:

//button[normalize-space()='Login']


41. Relative XPath for Tables

Relative XPath is useful for navigating tables.

HTML:

<table id="employees">

    <tbody>

        <tr>

            <td>John</td>

            <td>QA Tester</td>

        </tr>

    </tbody>

</table>

First cell:

//table[@id='employees']//tr[1]/td[1]

Second cell:

//table[@id='employees']//tr[1]/td[2]


42. Relative XPath for Specific Table Data

Suppose a table contains employee information:

<tr>

    <td>John</td>

    <td>QA Tester</td>

    <td>Mumbai</td>

</tr>

The XPath for the row containing John can be:

//tr[td[text()='John']]

The city cell in the same row can be located using:

//tr[td[text()='John']]/td[3]


43. Relative XPath Using Text and Parent Relationship

Suppose:

<div>

    <span>Username</span>

    <input type="text">

</div>

The input can be located relative to the Username text:

//span[text()='Username']/following-sibling::input

This approach is useful when the input itself does not have a unique attribute.


44. Relative XPath in Selenium WebDriver

Selenium uses the By.xpath() locator to work with Relative XPath.

WebElement username = driver.findElement(

    By.xpath("//input[@id='username']")

);

The element can then be used for further automation actions.


45. Relative XPath with sendKeys()

The sendKeys() method can enter text into an element located using Relative XPath.

driver.findElement(

    By.xpath("//input[@id='username']")

).sendKeys("admin");


46. Relative XPath with click()

The click() method can be used after locating a button or link.

driver.findElement(

    By.xpath("//button[@id='loginBtn']")

).click();


47. Relative XPath with getText()

The getText() method retrieves visible text from an element.

String message = driver.findElement(

    By.xpath("//div[@class='success-message']")

).getText();

 

System.out.println(message);


48. Relative XPath with getAttribute()

The getAttribute() method can retrieve attribute values.

String value = driver.findElement(

    By.xpath("//input[@id='username']")

).getAttribute("value");

 

System.out.println(value);


49. Relative XPath with findElements()

findElements() can locate multiple elements matching a Relative XPath.

List<WebElement> inputs = driver.findElements(

    By.xpath("//input")

);

 

System.out.println(inputs.size());


50. Relative XPath with Explicit Wait

Relative XPath can be used with explicit waits when an element needs to become available before interaction.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//button[@id='loginBtn']")

    )

);

 

loginButton.click();

JustAcademy's Selenium curriculum includes waits, synchronization, dynamic elements, and stable test execution strategies as part of Selenium automation training. Explore Selenium Training


51. Relative XPath in Page Object Model

Relative XPath locators can be stored in Page Object Model classes.

public class LoginPage {

    private WebDriver driver;

 

    private By username =

        By.xpath("//input[@id='username']");

 

    private By password =

        By.xpath("//input[@id='password']");

 

    private By loginButton =

        By.xpath("//button[@id='loginBtn']");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(String user, String pass) {

        driver.findElement(username).sendKeys(user);

        driver.findElement(password).sendKeys(pass);

        driver.findElement(loginButton).click();

    }

}


52. Complete Relative XPath Login Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class RelativeXPathExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(

            By.xpath("//input[@id='username']")

        ).sendKeys("admin");

 

        driver.findElement(

            By.xpath("//input[@id='password']")

        ).sendKeys("admin123");

 

        driver.findElement(

            By.xpath("//button[@id='loginBtn']")

        ).click();

 

        driver.quit();

    }

}


53. Relative XPath vs Absolute XPath

FeatureAbsolute XPathRelative XPath
Starting PointStarts from the rootCan locate from a selected context
Common Syntax/html/body/div//div
PathComplete DOM pathTargeted path
LengthUsually longerUsually shorter
DOM DependencyHighly dependent on hierarchyCan use attributes and relationships
Dynamic PagesCan be sensitive to structural changesCan be constructed around stable attributes
Example/html/body/div/form/input//input[@id='username']


54. Relative XPath vs ID Locator

FeatureRelative XPathID Locator
Selenium MethodBy.xpath()By.id()
IdentificationCan use attributes, text, relationships, and functionsUses ID attribute
FlexibilityHighDepends on ID availability
Example//input[@id='username']username


55. Advantages of Relative XPath

  • It does not require the complete DOM hierarchy.
  • It can create shorter XPath expressions.
  • It can use element attributes.
  • It can use visible text.
  • It supports XPath functions such as contains() and starts-with().
  • It supports parent-child relationships.
  • It supports sibling relationships.
  • It can be used for dynamic elements when stable parts of attributes are available.
  • It can be used with Page Object Model.
  • It can be used with explicit waits.


56. Disadvantages of Relative XPath

  • A poorly designed Relative XPath can match multiple elements.
  • Changing attributes can make attribute-based XPath invalid.
  • Incorrect indexes can identify the wrong element.
  • Complex XPath expressions can become difficult to understand.
  • Dynamic text can affect text-based XPath.
  • Using too many conditions can make the XPath unnecessarily complicated.


57. Common Mistakes in Relative XPath

  • Using the wrong attribute name.
  • Using incorrect attribute values.
  • Forgetting quotation marks around attribute values.
  • Using text() when the actual text is nested inside another element.
  • Using an incorrect index.
  • Creating an XPath that matches multiple elements.
  • Not validating the XPath in browser Developer Tools.
  • Using unstable dynamic attributes without a stable pattern.
  • Writing unnecessarily complicated XPath expressions.


58. How to Validate Relative XPath in Chrome

  1. Open the webpage in Chrome.
  2. Right-click the required element.
  3. Select Inspect.
  4. Open the Console tab.
  5. Use the $x() function.
  6. Enter the Relative XPath.
  7. Check the matching element.
  8. Use the validated XPath in Selenium.

Example:

$x("//input[@id='username']")

Another example:

$x("//button[text()='Login']")


59. How to Check Whether XPath is Unique

A good XPath should identify the intended element without unexpectedly matching unrelated elements.

In Chrome Console:

$x("//input[@id='username']")

If one intended element is returned, the expression can be investigated as a unique locator.

If multiple elements are returned, make the XPath more specific.

//form[@id='loginForm']//input[@id='username']


60. Best Practices for Relative XPath

  • Use stable attributes whenever possible.
  • Prefer unique attributes for element identification.
  • Use text-based XPath when visible text is stable.
  • Use contains() for stable portions of dynamic attributes.
  • Use starts-with() for predictable dynamic prefixes.
  • Avoid unnecessary XPath levels.
  • Use indexes only when necessary.
  • Validate XPath expressions in Developer Tools.
  • Keep XPath expressions readable.
  • Use Page Object Model to organize locators.
  • Review locators when the UI changes.
  • Use explicit waits when elements are dynamically loaded.


61. When Should You Use Relative XPath?

Relative XPath can be useful when:

  • An element has a stable ID, name, class, or other attribute that can be used in an XPath expression.
  • You need to locate an element using visible text.
  • You need to locate an element using a partial attribute value.
  • You need to navigate through parent-child relationships.
  • You need to locate sibling elements.
  • You are working with nested web elements.
  • You need to locate elements in dynamic web applications.
  • You need a targeted XPath instead of a complete DOM path.


62. Relative XPath for Dynamic Web Elements

Dynamic web elements can have changing IDs, classes, or other attributes. Relative XPath can be constructed using stable portions of those values.

Example:

<button id="submit_12345">Submit</button>

Instead of depending on the complete dynamic value, use:

//button[contains(@id,'submit_')]

This expression focuses on the stable part of the attribute.


63. Relative XPath Using Label Relationships

Labels can be useful reference points when input fields do not have unique attributes.

HTML:

<div>

    <label>Email</label>

    <input type="email">

</div>

XPath:

//label[text()='Email']/following-sibling::input

This finds the input associated with the Email label based on the sibling relationship.


64. Relative XPath for Login Form

<form id="loginForm">

    <label>Username</label>

    <input id="username" type="text">

    <label>Password</label>

    <input id="password" type="password">

    <button id="loginBtn">Login</button>

</form>

Relative XPath expressions:

//form[@id='loginForm']//input[@id='username']

//form[@id='loginForm']//input[@id='password']

//form[@id='loginForm']//button[@id='loginBtn']


65. Real-World Automation Flow

Open Browser

↓

Open Web Application

↓

Inspect Required Element

↓

Identify Stable Attribute or Relationship

↓

Create Relative XPath

↓

Validate XPath in Browser

↓

Use By.xpath()

↓

Locate WebElement

↓

Perform Action

↓

Validate Result

↓

Continue Test Execution


66. Relative XPath Quick Reference

PurposeExample
Tag Name//input
ID//input[@id='username']
Name//input[@name='username']
Class//input[@class='login-input']
Text//button[text()='Login']
Contains Text//button[contains(text(),'Login')]
Contains Attribute//input[contains(@id,'user')]
Starts With//input[starts-with(@id,'user_')]
Multiple Conditions//input[@type='text' and @name='username']
First Element(//input)[1]
Parent//input[@id='username']/parent::div
Ancestor//input[@id='username']/ancestor::form
Following Sibling//label[text()='Username']/following-sibling::input
Descendant//form[@id='loginForm']/descendant::input


67. Practical Exercise

Create a login page containing:

  • Username field.
  • Password field.
  • Remember Me checkbox.
  • Login button.
  • Forgot Password link.

Create Relative XPath expressions for each element.

//input[@id='username']

//input[@id='password']

//input[@type='checkbox']

//button[text()='Login']

//a[contains(text(),'Forgot Password')]

Validate every XPath using:

$x("YOUR_XPATH")


68. Complete Relative XPath Automation Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class RelativeXPathAutomation {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        WebElement username = driver.findElement(

            By.xpath("//input[@id='username']")

        );

 

        WebElement password = driver.findElement(

            By.xpath("//input[@id='password']")

        );

 

        WebElement loginButton = driver.findElement(

            By.xpath("//button[@id='loginBtn']")

        );

 

        username.sendKeys("admin");

        password.sendKeys("admin123");

        loginButton.click();

 

        driver.quit();

    }

}


69. Relative XPath Interview Questions

Q1. What is Relative XPath?

Relative XPath is an XPath expression used to locate an element without specifying its complete path from the root of the HTML document.

Q2. How does Relative XPath commonly start?

Relative XPath commonly starts with double forward slashes.

//

Q3. Give an example of Relative XPath.

//input[@id='username']

Q4. What is the difference between Absolute and Relative XPath?

Absolute XPath follows the complete hierarchy from the root, while Relative XPath can locate an element using attributes, text, relationships, functions, and other targeted conditions.

Q5. Can Relative XPath use attributes?

Yes. Attributes such as ID, name, class, type, href, and other HTML attributes can be used.

Q6. Can Relative XPath use text?

Yes. The text() function can be used to locate elements based on their visible text.

Q7. What is contains() in XPath?

contains() is an XPath function used to match a partial value of an attribute or text.

Q8. What is starts-with()?

starts-with() matches an attribute value that begins with a specified string.

Q9. Can Relative XPath use indexes?

Yes. Indexes can be used to identify a specific element among multiple matching elements.

Q10. How can Relative XPath be tested?

Relative XPath can be tested in the browser Console using the $x() function.

Q11. Can Relative XPath work with dynamic elements?

Yes. It can be constructed using stable portions of dynamic attributes, text, and element relationships.

Q12. Can Relative XPath be used with Selenium?

Yes. Selenium WebDriver supports Relative XPath through By.xpath().


70. Relative XPath Learning Checklist

  • Understand XPath basics.
  • Understand Relative XPath syntax.
  • Understand the double slash.
  • Locate elements using tag names.
  • Locate elements using ID.
  • Locate elements using name.
  • Locate elements using class.
  • Use multiple attributes.
  • Use and and or operators.
  • Use text().
  • Use contains().
  • Use starts-with().
  • Use normalize-space().
  • Use indexes.
  • Use parent and child relationships.
  • Use ancestor and descendant axes.
  • Use following-sibling and preceding-sibling.
  • Handle dynamic attributes.
  • Validate XPath in Chrome.
  • Use Relative XPath with Selenium WebDriver.
  • Use Relative XPath with Page Object Model.
  • Practice creating stable XPath expressions.


71. Key Points to Remember

  • Relative XPath commonly starts with //.
  • It does not require the complete DOM hierarchy.
  • It can use attributes to locate elements.
  • It can use visible text.
  • It supports XPath functions such as contains() and starts-with().
  • It supports parent, child, ancestor, descendant, and sibling relationships.
  • It can be used with dynamic elements when stable patterns are available.
  • Indexes can be used when multiple elements match.
  • XPath expressions should be validated before automation execution.
  • Stable and readable XPath expressions are easier to maintain.
  • Relative XPath is commonly used with Selenium WebDriver through By.xpath().


72. Conclusion

Relative XPath is an important Selenium locator technique that allows testers to locate web elements without depending on the complete path from the HTML root. It can identify elements using attributes, visible text, partial values, indexes, parent-child relationships, sibling relationships, and XPath functions.

Relative XPath is especially useful when creating Selenium automation scripts because it allows testers to build targeted locators around meaningful and stable characteristics of web elements. It can also be used with dynamic web elements when the XPath is designed around stable portions of their attributes or relationships.

JustAcademy's Selenium Automation Testing course covers Selenium WebDriver, locators including XPath and CSS selectors, WebElements, browser automation, waits, dynamic elements, TestNG, Page Object Model, framework development, and practical automation projects. Explore JustAcademy Selenium Training.

For additional course information, visit the JustAcademy Selenium Course Demo Registration page.

whatsapp