How to use Following-Sibling XPath in Selenium?

Master Following-Sibling XPath in Selenium to navigate sibling elements with precision. Run automated tests on real device cloud using BrowserStack Automate.

Get Started free
How to use Following-Sibling XPath in Selenium
Home Guide How to use Following-Sibling XPath in Selenium?

How to use Following-Sibling XPath in Selenium?

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.

Syntax of Following-Sibling XPath in Selenium

The syntax of following-sibling XPath in Selenium is as follows:

current_node//following-sibling::tagname
Copied
  • 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.

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>
Copied

XPath to Select the Immediate Next <h2> After “Title 1”

//h2[text()='Title 1']//following-sibling::h2[1]
Copied

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();
Copied

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>
Copied

XPath to Select All <li> Elements After “Item 1”

//li[text()='Item 1']//following-sibling::li
Copied

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());

}
Copied

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">
Copied

XPath to Select the Input Field After the “Username” Label

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

Use Case: Filling the input field dynamically.

javascript




await driver.findElement(By.xpath("//label[text()='Username']//following-sibling::input")).sendKeys("testuser");
Copied

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>
Copied

XPath to Select Age for “John”

//td[text()='John']//following-sibling::td
Copied

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);
Copied

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>
Copied

XPath to Select the <p> After “Section 1”

//h3[text()='Section 1']//following-sibling::p
Copied

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);
Copied

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>
Copied

XPath Expression:

//h2[text()='Product Name']/following-sibling::p
Copied

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>
Copied

XPath Expression:

//div[contains(text(),'Checkout')]/following-sibling::button
Copied

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>
Copied

XPath Expression:

//label[@for='email']/following-sibling::span[@class='error-msg']
Copied

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 AxisDescriptionExample Selection
following-siblingSelects all sibling elements that appear after the current nodeFinds next elements with the same parent.
preceding-siblingSelects 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:

Featurefollowing-siblingpreceding-sibling
Traversal DirectionSelects elements after the reference node.Selects elements before the reference node.
Selection ScopeSelects only sibling elements that share the same parent.Selects only sibling elements that share the same parent.
Common Use CaseSelecting 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.

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]
Copied

Example (Bad XPath – Too Generic):

//div//following-sibling::p
Copied

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]
Copied

Selecting All Following Paragraphs:

//h2[text()='Heading 1']//following-sibling::p
Copied

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]
Copied

Example: Select the following input field after a label

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

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
Copied

Example (Efficient XPath – Direct Selection):

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

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>
Copied

Incorrect XPath (Selects All Paragraphs)

//h2[text()='Title 1']//following-sibling::p
Copied

Solution: Use indexing to select a specific sibling.

//h2[text()='Title 1']//following-sibling::p[1]
Copied

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>
Copied

Incorrect XPath (Fails if Username Changes)

//h2[text()='Welcome, User123']//following-sibling::p
Copied

Solution: Use contains() for partial matching.

//h2[contains(text(),'Welcome')]//following-sibling::p
Copied

This works even if the username changes dynamically.

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>
Copied

Incorrect XPath (Fails if Element is Not Rendered Yet)

//h2[text()='Profile']//following-sibling::p
Copied

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

);
Copied

This waits up to 5 seconds for the element to appear.

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>
Copied

Incorrect XPath (Fails Due to Extra Spaces)

//h2[text()='Page Title']//following-sibling::p
Copied

Solution: Use normalize-space() to ignore extra spaces.

//h2[normalize-space()='Page Title']//following-sibling::p
Copied

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>
Copied

Working XPath Before Update

//h2[text()='Contact Us']//following-sibling::p
Copied

Updated HTML (Extra Div Introduced)

<h2>Contact Us</h2>

<div>

    <p>Email: support@example.com</p>

</div>
Copied

Incorrect XPath (Breaks Due to Additional <div>)

//h2[text()='Contact Us']//following-sibling::p
Copied

Solution: Use descendant:: to handle structural changes.

//h2[text()='Contact Us']//following-sibling::div//p
Copied

Works even if <div> is introduced.

BrowserStack Automate Banner

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.

Talk to an Expert

Useful Resources for Selenium

Methods, Classes, and Commands

Configuration

XPath

Locators and Selectors

Waits in Selenium

Frameworks in Selenium

Miscellaneous

Best Practices, Tips and Tricks

Design Patterns in Selenium: Page Object Model and Page Factory

Action Class

TestNG and Selenium

JUnit and Selenium

Use Cases

Types of Testing with Selenium

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.

Tags
Automation Testing Real Device Cloud Selenium