XPath is a powerful technique for locating web elements in Selenium, especially when handling dynamic and complex web structures.
Among its various axes, Following-Sibling XPath helps identify elements that share the same parent and appear after a specified element. This method is particularly useful in structured layouts like tables, lists, and dynamically generated content.
This article will explain Following-Sibling XPath, its usage with examples, and best practices for implementing it in Selenium.
What are XPath Axes in Selenium?
XPath Axes in Selenium are used to navigate through elements in the XML or HTML document relative to a particular node.
These axes help locate elements based on their relationship with other elements, making it easier to find elements dynamically.
This article explains Following-Sibling XPath in Selenium in detail.
To explore other XPath types in detail, check out How to use XPath in Selenium.
What is Following-Sibling XPath in Selenium?
The following-sibling XPath in Selenium is used to locate elements that share the same parent as the current node and appear after it in the DOM structure.
Must Read: Quick XPath Locators Cheat Sheet
Syntax of Following-Sibling XPath in Selenium
The syntax of following-sibling XPath in Selenium is as follows:
current_node//following-sibling::tagname
- current_node: The reference element from which the search begins.
- following-sibling::tagname: Selects all sibling elements with the specified tag name that appear after the reference element.
Must Read: Mastering Dynamic XPath in Selenium
Use Cases of following-sibling XPath in Selenium
The following-sibling XPath is useful for selecting elements that appear after a reference element within the same parent.
Below are some key use cases:
1. Selecting the Next Immediate Sibling Element
When you need to interact with an element that immediately follows another element.
Example HTML:
<div> <h2>Title 1</h2> <h2>Title 2</h2> <h2>Title 3</h2> </div>
XPath to Select the Immediate Next <h2> After “Title 1”
//h2[text()='Title 1']//following-sibling::h2[1]
Use Case: Clicking on the next title after a specific one.
javascript await driver.findElement(By.xpath("//h2[text()='Title 1']//following-sibling::h2[1]")).click();
Learn More: How to Find Elements by ID in Selenium
2. Selecting All Following Siblings
When you need to retrieve or interact with multiple sibling elements after a given reference.
Example HTML:
<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>
XPath to Select All <li> Elements After “Item 1”
//li[text()='Item 1']//following-sibling::li
Use Case: Fetching all menu items that appear after a given one.
javascript let items = await driver.findElements(By.xpath("//li[text()='Item 1']//following-sibling::li")); for (let item of items) { console.log(await item.getText()); }
3. Selecting Elements Dynamically in Forms
When form fields are not uniquely identified, but their labels can be used to locate corresponding input fields.
Example HTML:
<label>Username</label> <input type="text" id="username"> <label>Password</label> <input type="password" id="password">
XPath to Select the Input Field After the “Username” Label
//label[text()='Username']//following-sibling::input
Use Case: Filling the input field dynamically.
javascript await driver.findElement(By.xpath("//label[text()='Username']//following-sibling::input")).sendKeys("testuser");
4. Extracting Data from Tables
When you need to fetch a specific column value in a table based on a reference value.
Example HTML:
<table> <tr> <td>John</td> <td>25</td> </tr> <tr> <td>Jane</td> <td>30</td> </tr> </table>
XPath to Select Age for “John”
//td[text()='John']//following-sibling::td
Use Case: Extracting age dynamically for a specific name.
javascript let age = await driver.findElement(By.xpath("//td[text()='John']//following-sibling::td")).getText(); console.log(age);
5. Navigating Through Nested Elements
When a structure has repeated elements (e.g., sections, divs) you need to locate related elements.
Example HTML:
<div class="section"> <h3>Section 1</h3> <p>Description 1</p> </div> <div class="section"> <h3>Section 2</h3> <p>Description 2</p> </div>
XPath to Select the <p> After “Section 1”
//h3[text()='Section 1']//following-sibling::p
Use Case: Retrieving a description under a specific section.
javascript let description = await driver.findElement(By.xpath("//h3[text()='Section 1']//following-sibling::p")).getText(); console.log(description);
How to Use Following-Sibling for Elements with Specific Text or Attributes
The following-sibling:: XPath axis allows testers to select sibling elements after a reference element within the same parent.
This technique is useful to deal with dynamic tables, lists, forms, or nested elements where direct element selection isn’t feasible.
By combining following-sibling with text(), contains(), and attribute filters, you can precisely target the required elements.
1. Using Following-Sibling with Specific Text
Select a paragraph <p> that follows an <h2> heading with specific text.
HTML Structure:
<h2>Product Name</h2> <p>Price: $100</p> <p>Availability: In Stock</p>
XPath Expression:
//h2[text()='Product Name']/following-sibling::p
This XPath selects the first <p> that follows the <h2> with text “Product Name”.
2. Using Following-Sibling with contains(text()) for Partial Matches
Select a button that follows a <div> containing the text “Checkout”.
HTML Structure:
<div>Proceed to Checkout</div> <button>Pay Now</button>
XPath Expression:
//div[contains(text(),'Checkout')]/following-sibling::button
This selects the <button> that follows the <div> containing “Checkout”, even if the text isn’t an exact match.
3. Using Following-Sibling to Find an Element with a Specific Attribute
Select a <span> element that follows a <label> with the attribute for=’email’.
HTML Structure:
<label for="email">Email Address</label> <span class="error-msg">Invalid Email</span>
XPath Expression:
//label[@for='email']/following-sibling::span[@class='error-msg']
This selects the <span> element with the class “error-msg” that follows the <label> for “email”.
Difference between Preceding-Sibling and Following-Sibling XPath axes.
The preceding-sibling and following-sibling XPath axes are used to navigate through sibling elements in the DOM.
The main difference is the traversal direction:
XPath Axis | Description | Example Selection |
---|---|---|
following-sibling | Selects all sibling elements that appear after the current node | Finds next elements with the same parent. |
preceding-sibling | Selects all sibling elements that appear before the current node. | Finds previous elements with the same parent. |
Also, there are some major differences between following-sibling and preceding-sibling, as shown below:
Feature | following-sibling | preceding-sibling |
---|---|---|
Traversal Direction | Selects elements after the reference node. | Selects elements before the reference node. |
Selection Scope | Selects only sibling elements that share the same parent. | Selects only sibling elements that share the same parent. |
Common Use Case | Selecting next elements (e.g., next form field, next table row). | Selecting previous elements (e.g., previous form field, previous table row). |
Best Practices for using Following-Sibling XPath in Selenium
Using following-sibling XPath effectively in Selenium requires writing robust, maintainable, and efficient locators.
Also Read: XPath in Appium: Tutorial
Below are the best practices to follow:
1. Use Specific Element Identifiers to Improve Accuracy
Always try to use an identifier (ID, class, text) in the base element before using following-sibling.
Avoid using generic tags like //div//following-sibling::div, as they may return unintended results.
Example (Good XPath):
//h2[text()='Section Title']//following-sibling::p[1]
Example (Bad XPath – Too Generic):
//div//following-sibling::p
2. Use Indexing Carefully
The [1] index selects only the immediate next sibling.
- If selecting all siblings, avoid unnecessary indexing.
- If indexing is necessary, ensure the page structure remains consistent.
Selecting the First Following Paragraph:
//h2[text()='Heading 1']//following-sibling::p[1]
Selecting All Following Paragraphs:
//h2[text()='Heading 1']//following-sibling::p
3. Combine following-sibling with Other Attributes
Improve accuracy by combining following-sibling with attributes like @class, @id, or contains(text()).
Example: Select the first paragraph after a heading with a specific class
//h2[@class='title']//following-sibling::p[1]
Example: Select the following input field after a label
//label[text()='Email']//following-sibling::input[@type='text']
4. Be Mindful of Performance
XPath queries can be slow if they traverse large DOM trees.
- Avoid overly broad queries.
- Use By.id, By.className, or By.cssSelector when possible, as they are faster.
Example (Inefficient XPath – Unnecessary Traversal):
//*[text()='Username']//following-sibling::input
Example (Efficient XPath – Direct Selection):
//label[text()='Username']//following-sibling::input[@type='text']
Common Challenges with Following-Sibling XPath and Solutions
Using following-sibling XPath in Selenium can be powerful but comes with some challenges.
Below are common issues and solutions to ensure accurate element selection and efficient test automation.
1. Multiple Matching Elements
When multiple sibling elements exist, following-sibling::tagname may return more than one match, leading to unintended selections.
Example HTML:
<div> <h2>Title 1</h2> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> </div>
Incorrect XPath (Selects All Paragraphs)
//h2[text()='Title 1']//following-sibling::p
Solution: Use indexing to select a specific sibling.
//h2[text()='Title 1']//following-sibling::p[1]
This selects only the first paragraph after the heading.
2. Dynamic Text or Attribute Changes
Elements with changing text or dynamic attributes might not match exact XPath queries.
Example HTML:
<h2>Welcome, User123</h2> <p>Dashboard Overview</p>
Incorrect XPath (Fails if Username Changes)
//h2[text()='Welcome, User123']//following-sibling::p
Solution: Use contains() for partial matching.
//h2[contains(text(),'Welcome')]//following-sibling::p
This works even if the username changes dynamically.
Also Read: Xpath Vs CSS Selector: Key Differences
3. Invisible or Delayed Elements
Some elements may not be immediately available in the DOM due to lazy loading or JavaScript rendering.
Example HTML (Delayed Rendering)
<h2>Profile</h2> <p style="display: none;">User Info</p>
Incorrect XPath (Fails if Element is Not Rendered Yet)
//h2[text()='Profile']//following-sibling::p
Solution: Use Explicit Waits in Selenium to wait for the element.
javascript let userInfo = await driver.wait( until.elementLocated(By.xpath("//h2[text()='Profile']//following-sibling::p")), 5000 );
This waits up to 5 seconds for the element to appear.
Must Read: How to Lazy Load Images in Javascript
4. Extra Whitespaces in Text Content
Some elements may contain extra spaces, causing XPath to fail.
Example HTML:
<h2> Page Title </h2> <p>Content Here</p>
Incorrect XPath (Fails Due to Extra Spaces)
//h2[text()='Page Title']//following-sibling::p
Solution: Use normalize-space() to ignore extra spaces.
//h2[normalize-space()='Page Title']//following-sibling::p
Works even if extra spaces exist.
5. Unstable DOM Structure
If the webpage structure changes (e.g., extra <div> wrappers are added), XPath may break.
Example HTML (Before Update)
<h2>Contact Us</h2> <p>Email: support@example.com</p>
Working XPath Before Update
//h2[text()='Contact Us']//following-sibling::p
Updated HTML (Extra Div Introduced)
<h2>Contact Us</h2> <div> <p>Email: support@example.com</p> </div>
Incorrect XPath (Breaks Due to Additional <div>)
//h2[text()='Contact Us']//following-sibling::p
Solution: Use descendant:: to handle structural changes.
//h2[text()='Contact Us']//following-sibling::div//p
Works even if <div> is introduced.
Why Run Selenium Tests on Real Devices?
Testing on real devices ensures accurate, real-world results that emulators cannot replicate. Factors like browser behavior, network conditions, hardware performance, and real user interactions impact web applications, making testing on real device cloud essential.
A cloud-based platform like BrowserStack Automate provides instant access to 3,500+ real devices and browsers, eliminating the need for an in-house device lab. It enables seamless manual and automated testing across different OS, browsers, and mobile devices in real user conditions.
Key Benefits of using BrowserStack Automate for Selenium Testing
Below are the key reasons why you should use Browsertack Automate to run Selenium Tests:
- Accurate Browser & OS Behavior: Ensures correct rendering, JavaScript execution, and UI consistency.
- Real Network Conditions: Tests performance under Wi-Fi, 4G, 5G, and slow networks.
- Hardware Variability: Considers CPU, RAM, battery constraints, and real device responsiveness.
- Touch & Gesture Support: Validates real interactions like swipe, pinch, and tap.
- Real Sensor Testing: Ensures GPS, camera, microphone, and biometric authentication work correctly.
- Cross Browser Compatibility: Tests apps on Chrome, Safari, Edge, Firefox, and more.
- Faster Test Execution: Supports Selenium, Cypress, Playwright, and Appium for parallel and automated testing.
- Seamless UX Testing: Evaluates dark mode, low battery performance, background behavior, and push notifications.
Useful Resources for Selenium
Methods, Classes, and Commands
- Selenium Commands every Developer or Tester must know
- Selenium WebElement Commands
- Desired Capabilities in Selenium Webdriver
- Assert and Verify Methods in Selenium
- Understanding System setProperty in Selenium
- Select Class in Selenium : How to select a value in dropdown list?
- SendKeys in Selenium WebDriver
- getAttribute() method in Selenium: What, Why, and How to use
- How does Selenium isDisplayed() method work?
- findElement vs findElements in Selenium
- Types of Listeners in Selenium (with Code Examples)
- How to set Proxy in Firefox using Selenium WebDriver?
Configuration
- How to set up Selenium on Visual Studio
- How to configure Selenium in Eclipse
- Maven Dependency Management with Selenium
- How to Build and Execute Selenium Projects
XPath
- How to use XPath in Selenium?
- How to find element by XPath in Selenium with Example
- Top Chrome Extensions to find Xpath in Selenium
Locators and Selectors
- Locators in Selenium: A Detailed Guide
- CSS Selector in Selenium: Locate Elements with Examples
- How to Create Object Repository in Selenium
Waits in Selenium
- Wait Commands in Selenium C and C#
- Selenium Wait Commands: Implicit, Explicit, and Fluent Wait
- Understanding Selenium Timeouts
- Understanding ExpectedConditions in Selenium
- Understanding Role of Thread.sleep() in Selenium
Frameworks in Selenium
- Data Driven Framework in Selenium
- Implementing a Keyword Driven Framework for Selenium: A Practical Guide
- Hybrid Framework in Selenium
Miscellaneous
- How to create Selenium test cases
- How to set Proxy in Selenium?
- Difference between Selenium Standalone server and Selenium server
- Exception Handling in Selenium WebDriver
- How to use JavascriptExecutor in Selenium
- How to run your first Selenium test script
- Parallel Testing with Selenium
Best Practices, Tips and Tricks
- Top 5 Challenges Faced During Automation Selenium Testing
- 5 Selenium tricks to make your life easier
- 6 Things to avoid when writing Selenium Test Scripts
- Best Practices for Selenium Test Automation
- Why you should pay attention to flaky Selenium tests
- How to start with Selenium Debugging
- How to make your Selenium test cases run faster
- How to upgrade from Selenium 3 to Selenium 4
- Why you should move your testing to a Selenium Cloud?
Design Patterns in Selenium: Page Object Model and Page Factory
- Design Patterns in Selenium
- Page Object Model and Page Factory in Selenium
- Page Object Model and Page Factory in Selenium C#
- Page Object Model in Selenium and JavaScript
- Page Object Model and Page Factory in Selenium Python
Action Class
- How to handle Action class in Selenium
- How to perform Mouse Hover Action in Selenium
- Understanding Click Command in Selenium
- How to perform Double Click in Selenium?
- How to Drag and Drop in Selenium?
- How to Scroll Down or Up using Selenium Webdriver
- How To verify Tooltip Using Selenium
TestNG and Selenium
- Database Testing using Selenium and TestNG
- How to use DataProvider in Selenium and TestNG?
- All about TestNG Listeners in Selenium
- How to run parallel test cases in TestNG
- How to use TestNG Reporter Log in Selenium: Tutorial
- Prioritizing tests in TestNG with Selenium
JUnit and Selenium
- Understanding JUnit assertions for Selenium Testing with Examples
- How to run JUnit Parameterized Test in Selenium
- How to write JUnit test cases
- JUnit Testing Tutorial: JUnit in Java
- How to create JUnit Test Suite? (with Examples)
Use Cases
- Handling Login Popups in Selenium WebDriver and Java
- How to Launch Browser in Selenium
- How to handle Alerts and Popups in Selenium?
- How to get Selenium to wait for a page to load
- How to Find Element by Text in Selenium: Tutorial
- How to Read/Write Excel Data using Apache POI Selenium
- How to handle Captcha in Selenium
- How to handle multiple windows in Selenium?
- How to handle Multiple Tabs in Selenium
- How to find broken links in Selenium
- How to handle Cookies in Selenium WebDriver
- How to handle iFrame in Selenium
- How to handle Web Tables in Selenium
- How To Validate Text in PDF Files Using Selenium Automation
- Get Current URL in Selenium using Python: Tutorial
Types of Testing with Selenium
- Different Testing Levels supported by Selenium
- How to perform UI Testing with Selenium
- Regression Testing with Selenium: Tutorial
- UI Automation using Python and Selenium: Tutorial
- How to Run Visual Tests with Selenium: Tutorial
- How to perform ETL Automation using Selenium
- Cross Browser Testing in Selenium : Tutorial
Conclusion
Mastering Following-Sibling XPath in Selenium enables efficient navigation through web elements, especially in cases where elements lack unique attributes.
Using the following-sibling:: axis, testers can locate elements that appear after a reference element within the same parent, making it a valuable technique for handling dynamic tables, lists, and structured content.
While Following-Sibling XPath is a powerful locator strategy, it should be used strategically with other robust and maintainable techniques.