Power Your Software Testing
with AI and Cloud
Supercharge QA with AI for Faster & Smarter Software Testing

Learn how to use following-sibling XPath in Selenium to locate dynamic web elements, handle forms, tables, and pagination for reliable automation tests.
Published on: October 29, 2025
When working with complex or dynamic web applications, locating elements that share the same parent can be challenging. The following-sibling XPath in Selenium is a powerful axis that helps you identify elements that appear immediately after a specific element in the DOM hierarchy.
It’s especially useful when elements don’t have unique attributes but maintain a consistent structural relationship, such as form fields, lists, or pagination links. Using the following-sibling XPath ensures your locators stay reliable even when element positions or IDs change slightly.
What Is Following-Sibling XPath in Selenium?
Following-sibling XPath in Selenium is a locator strategy that allows you to identify elements that come after a specific reference element under the same parent, without relying on unique IDs or classes. Unlike absolute XPath, it dynamically traverses the DOM based on element relationships, making it useful for handling lists, tables, or repetitive page structures.
Where to Apply Following-Sibling XPath in Selenium?
Following-sibling XPath is useful when elements are related and positioned sequentially in the DOM. It helps locate elements dynamically and maintain test reliability.
How to Set Up Following-Sibling XPath in Selenium?
To implement the following-sibling XPath in Selenium, ensure your environment and tools are ready for seamless dynamic element selection.
How to Avoid Common Mistakes in Following-Sibling XPath?
Following-sibling XPath is powerful but prone to errors if not used carefully. Knowing common pitfalls ensures reliable, maintainable tests.
When Should I Avoid Using Following-Sibling in Selenium Scripts?
You should avoid using following-sibling when the DOM structure changes frequently or when more reliable locators such as IDs, class names, or CSS selectors are available. XPath expressions that depend on element order can easily break if new elements are inserted or removed. In such cases, prefer attribute-based locators or semantic selectors to improve test reliability.
XPath axes are a core feature of XPath that allow us to navigate through the DOM structure relative to a specific element.
They allow us to traverse in different directions, referring to the element itself (self), moving up (parent), down (child), or sideways (sibling), to define relationships between elements.
This makes it possible to find elements dynamically based on their position or relation to other elements, which is especially useful in complex or changing UIs where static locators may break. In test automation, XPath is often used when other Selenium locators, like tags or CSS class names, are not enough to select all elements in the DOM.
The common XPath axes are:
The following-sibling XPath is used to locate all the elements that share the same parent and appear after the current node in the DOM hierarchy. In simpler terms, it allows you to move sideways to the next sibling elements under the same parent.
Syntax: The syntax for the following-sibling in Selenium is:
current_node/following-sibling::tagnameOptional Indexing
Note: XPath indexing is 1-based, so [1] refers to the first matching sibling.
Just to understand the working of the following-sibling XPath in Selenium, let’s take an example.
Example: Selecting an Input Field in a Form
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" />
<label for="password">Password:</label>
<input type="password" id="password" />
<button type="submit">Login</button>
</div>
To select the password <input> using its <label> as a reference:
//label[@for='password']/following-sibling::input[@id='password']The following-sibling axis selects all the sibling elements that match the criteria. So, if multiple siblings of the same type exist, you can further refine the selection by using an index.
//label[@for='password']/following-sibling::input[1]Here, [1] ensures that only the first matching sibling <input> is selected.
Note: Run your automation test script at scale across 3000+ browsers and OS combinations. Try LambdaTest Now!
You can apply the following-sibling XPath in Selenium automation testing when you need to locate elements that appear after a specific node within the same parent. It’s especially useful for handling structured layouts like form fields, table rows, or labels linked to input fields, where element positions remain consistent.
Let’s discuss some real-time examples in web automation where the following-sibling XPath can be useful for precise element selection.
When you need to interact with the element that directly follows a specific element on a web page, you can use the following-sibling XPath to locate it precisely.
Test Scenario:
Example:
Consider a pagination component.
<div class="pagination">
<a class="page" href="?page=1">1</a>
<a class="page" href="?page=2">2</a>
<a class="page" href="?page=3">3</a>
</div>To select and click the immediate next page after “1”, use the following-sibling XPath as shown below:
//a[text()='1']/following-sibling::a[1]This would select:
<a class="page" href="?page=2">2</a>When you need to interact with all the sibling elements following a specific element on a web page, you can use the following-sibling XPath to select them efficiently.
Test Scenario:
Example:
Consider a navigation menu.
<ul class="nav">
<li>Home</li>
<li>Products</li>
<li>Services</li>
<li>Contact</li>
</ul>To select all menu items that come after “Products,” use the following-sibling XPath as shown below:
//li[text()='Products']/following-sibling::liThis would select:
<li>Services</li>
<li>Contact</li>When form fields lack unique IDs or classes, but their labels can be used as anchors, you can use the following-sibling XPath to locate the corresponding input fields dynamically.
Test Scenario:
Example:
Consider a login form.
<label>Username</label>
<input type="text" name="username">
<label>Password</label>
<input type="password" name="password">To select the input field that comes right after the “Username” label, use the following-sibling XPath as shown below:
//label[text()='Username']/following-sibling::inputThis would select:
<input type="text" name="username">When elements appear conditionally on a web page, you can use the following-sibling in XPath to locate them reliably.
Test Scenario:
Example:
Consider a login form.
<form id="login">
<label>Username</label>
<input type="text" name="username">
<label>Password</label>
<input type="password" name="password">
</form>
<div class="error">Invalid credentials</div>To select the error message that appears after an invalid form submission using the following-sibling XPath as shown below:
//form[@id='login']/following-sibling::div[@class='error']This would select:
<div class="error">Invalid credentials</div>When you need to fetch specific values from table rows or columns based on a reference cell, you can use the following-sibling XPath for precise selection.
Test Scenario:
Example:
Consider a product table.
<table>
<tr>
<td>Product A</td>
<td>$50</td>
<td>In Stock</td>
</tr>
<tr>
<td>Product B</td>
<td>$75</td>
<td>Out of Stock</td>
</tr>
</table>To select the price of “Product B”, use the following-sibling XPath as shown below:
//td[text()='Product B']/following-sibling::td[1]This would select:
<td>$75</td>When a page contains repeated or nested structures, you can use following-sibling in XPath to select elements that appear directly after a known reference node.
Test Scenario:
Example:
Consider an accordion section.
<div class="accordion">
<h3>Section 1</h3>
<div class="panel">Content 1</div>
<h3>Section 2</h3>
<div class="panel">Content 2</div>
</div>To select the panel immediately following “Section 1”, use the following-sibling XPath as shown below:
//h3[text()='Section 1']/following-sibling::div[@class='panel'][1]This would select:
<div class="panel">Content 1</div>Using the following-sibling in XPath in a real test case helps you navigate dynamic web elements, like pagination links or sequential form fields, without hardcoding element positions. It ensures your automation scripts remain robust even when the page structure changes slightly.
Let us create an automation test using the following-sibling in XPath for a simple pagination scenario.
Test Scenario:

Before implementing the pagination test using the following-sibling XPath, make sure you have the following setup:
Prerequisites:
Make sure you have the following libraries and tools already installed.
node -v
npm -vnpm install @wdio/cli @wdio/globals --save-devnpm install mocha --save-devnpm install chai --save-devnpm install chromedriver --save-devYou can implement this automation test for the scenario using the WebdriverIO framework, but before you jump to the entire code, you need to get the XPath for the next page.
Get the XPath for the Next Page:
Here, the XPath for the next page would be:
//li[@class='active page-item']/following-sibling::li[1]/aThe index [1] selects the first sibling <li>after the active page (context node), which corresponds to the next page link.
Code Implementation:
/import { browser, $ } from "@wdio/globals";
describe("LambdaTest Playground Pagination Test", () => {
before(async () => {
// Visit the LambdaTest Playground E-Commerce Store
await browser.url("https://ecommerce-playground.lambdatest.io/");
});
it("Navigate to Laptop product listing and click next page", async () => {
// Go to the laptop product listing page
const laptopCategory = await $("//h4[normalize-space()='Laptops']");
await laptopCategory.click();
// Wait for the product listing page to load
const productListUrl = await browser.getUrl();
expect(productListUrl).toContain("route=product/category&path=18");
// Identify the current active page number
const activePageEl = await $("//li[@class='active page-item']");
const currentPageText = await activePageEl.getText();
const currentPage = parseInt(currentPageText.trim());
console.log("Current active page is:", currentPage);
// Click the next page using following-sibling
const nextPage = await $(
"//li[@class='active page-item']/following-sibling::li[1]/a"
);
await nextPage.click();
// Verify that page has navigated to next page
const newProductListUrl = await browser.getUrl();
expect(newProductListUrl).toContain(`page=${currentPage + 1}`);
});
});

Test Execution:

To further enhance test execution speed and scalability, you can move your automation tests to a cloud platform. Local execution works fine but is limited by available infrastructure, browser instances, and system resources. Running tests in the cloud allows parallel execution across multiple browsers and devices, reducing overall test time significantly.
By leveraging cloud-based platforms like LambdaTest, you can perform both manual and Selenium testing at scale across 3,000+ browsers and operating systems and 10,000+ real device environments, all with minimal configuration changes.
To get started with LambdaTest, follow the steps given below:
npm i wdio-lambdatest-service --save-dev// wdio.conf.js
exports.config = {
// ...
user: process.env.LT_USERNAME,
key: process.env.LT_ACCESS_KEY,
logFile : './logDir/api.log',
product : 'appAutomation',
services: [
['lambdatest', {
tunnel: true
}]
],
// ...
};
capabilities: [
{
browserName: "Chrome",
browserVersion: "dev",
"LT:Options": {
username: process.env.LT_USERNAME,
accessKey: process.env.LT_ACCESS_KEY,
platformName: "Windows 10",
project: "Following Sibling XPath Axis Demo",
build: "Build 1",
name: "Pagniation Test",
w3c: true,
plugin: "node_js-webdriverio",
},
},
],
Your final configuration file must look like this:
export const config = {
runner: "local",
specs: ["./test/specs/**/*.js"],
exclude: [],
maxInstances: 10,
user: process.env.LT_USERNAME,
key: process.env.LT_ACCESS_KEY,
logFile: "./logDir/api.log",
product: "appAutomation",
services: [
[
"lambdatest",
{
tunnel: true,
},
],
],
capabilities: [
{
browserName: "Chrome",
browserVersion: "dev",
"LT:Options": {
username: process.env.LT_USERNAME,
accessKey: process.env.LT_ACCESS_KEY,
platformName: "Windows 10",
project: "Following Sibling XPath Axis Demo",
build: "Build 1",
name: "Pagniation Test",
w3c: true,
plugin: "node_js-webdriverio",
},
},
],
logLevel: "info",
bail: 0,
waitforTimeout: 10000,
connectionRetryTimeout: 120000,
connectionRetryCount: 3,
framework: "mocha",
reporters: ["spec"],
mochaOpts: {
ui: "bdd",
timeout: 60000,
},
};

Test Execution:
Run the following command given below:
npm run wdioThe test has been executed successfully in the LambdaTest Cloud Grid. You can verify the result in your LambdaTest Automation Dashboard.

This test shows how you can effectively use following-sibling XPath to navigate pagination dynamically, without hardcoding the next page number.
To get started, check out this guide on Selenium testing with LambdaTest.
While the following-sibling axis is powerful, if used carelessly, you may encounter issues. Below are some common pitfalls faced by testers, along with ways to avoid them.
If multiple elements match the same XPath expression, following-sibling::tagname may return multiple matches, resulting in unintended element selections.
Solution:
Solution:
//label[text()='Username']/following-sibling::input
//form[@id='login']/following-sibling::div[@class='error']If an element’s text or attributes change dynamically, relying on exact matches may cause failures.
Code Example of Exact Match:
<h2>Messages Today: 7</h2>
<p>Unread messages summary</p>Here, the number of messages “7” is a dynamic value and may change. Using an exact text match is likely to cause the test to fail.
//h2[text()='Messages Today: 7']/following-sibling::pSolution:
Instead of exact matching, use partial matching with contains().
//h2[contains(text(),'Messages Today')]/following-sibling::pElements may not be rendered or visible immediately due to the way the browser’s rendering engine processes the page. To handle this, you can use Selenium waits, which allow your test to pause until elements are present, visible, and ready for interaction.
Common Causes Include:
Solution:
WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(d -> {
WebElement el = d.findElement(By.id("elementId"));
return (el.isDisplayed() && el.isEnabled()) ? el : null;
});
element.click();WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
element.sendKeys("test");wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loadingSpinner")));Extra spaces, line breaks, or hidden text nodes may cause mismatches and test failures.
Code Example of Whitespaces:
<div>
Welcome
User
</div>If you try a direct text match as below, it will fail.
//div[text()='Welcome User']Solution:
Use normalize-space() in your XPath to trim unnecessary whitespace.
//div[normalize-space(.)='Welcome User']The following-sibling axis in Xpath is highly dependent on the DOM layout. Changes like adding, removing, or reordering elements may break your XPath.
Solution:
Overly broad XPath queries can slow down test execution.
Code Example of Performance Issues:
//*[following-sibling::div]This searches for all elements in the DOM that have a following-sibling <div>, which is inefficient in large applications and can cause test lag.
Though Selenium offers many locator strategies, there’s often debate on when to use XPath vs CSS selectors, as each has its own advantages and trade-offs in terms of readability, flexibility, and performance.
Using the following-sibling axis can make your automation scripts powerful. By implementing the following strategies, you can ensure that your tests are efficient, maintainable, and robust.
Keep the XPath expression as simple and straightforward as possible. This is crucial for maintaining the readability and maintainability of tests and ensuring there are no errors as the application evolves. When writing XPath in Selenium, always combine the following-sibling with conditions like text(), @class, or @id to avoid selecting unintended siblings.
Example:
//label[text()='Username']/following-sibling::input//form[@id='login']/following-sibling::div[@class='error']Numeric indexing allows precise targeting within a set of matched siblings. Use [n] to select the exact sibling when multiple matches exist.
Example:
//h3[text()='Section 1']/following-sibling::div[1]The following-sibling can be combined with other XPath axes, like descendant or child, to navigate nested or dynamic content efficiently.
Example:
<div class="section">
<h2>Introduction</h2>
<div class="content">
<button>Read More</button>
</div>
</div>To select the Read More button from the Introduction heading, the XPath can be:
//h2[text()='Introduction']/following-sibling::div/child::buttonor using shorthand:
//h2[text()='Introduction']/following-sibling::div/buttonThe following-sibling XPath axis provides a precise way to select elements that appear after a reference node within the same parent. Its strength and versatility make it invaluable for navigating complex web structures, including dynamic content, interactive menus, and intricate forms.
However, over-reliance on following-sibling without combining it with other XPath axes, conditions, or functions can lead to brittle or suboptimal locators. But by using it thoughtfully alongside other XPath techniques, testers can create robust, maintainable, and reliable automation scripts.
Did you find this page helpful?
More Related Hubs
Start your journey with LambdaTest
Get 100 minutes of automation test minutes FREE!!