How to use Following-Sibling XPath in Selenium?

On This Page What are XPath Axes in Selenium?January 13, 2026 · 13 min read · Tool Comparison

How to use Following-Sibling XPath in Selenium?

XPathis a powerful technique for locate web elements in Selenium, especially when handling dynamic and complex web structures.

Among its various axis,Following-Sibling XPathhelps identify elements that share the same parent and appear after a specified element. This method is peculiarly utilitarian in structured layout like tables, lean, and dynamically generated content.

This clause will excuseFollowing-Sibling XPath, its employment with exemplar, and best practices for implementing it in Selenium.

What are XPath Axes in Selenium?

XPath Axes in are utilise to navigate through elements in the XML or HTML document relative to a particular node.

These axes help locate elements ground on their relationship with former ingredient, get it easygoing to find elements dynamically.

This article explainsFollowing-Sibling XPath in Seleniumin detail.

To explore other XPath case in detail, assure out.

What is Following-Sibling XPath in Selenium?

The following-siblingXPath in Selenium is used to that parcel the like parent as the current node and appear after it in the.

Must Read:

Syntax of Following-Sibling XPath in Selenium

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

current_node//following-sibling: :tagname
  • current_node: The quotation factor from which the search commence.
  • following-sibling: :tagname: Selects all sibling constituent with the specified tag name that seem after the reference ingredient.

Must Read:

Use Cases of following-sibling XPath in Selenium

The following-siblingXPath is utilitarian for take elements that appear after a reference ingredient 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:

& lt; div & gt; & lt; h2 & gt; Title 1 & lt; /h2 & gt; & lt; h2 & gt; Title 2 & lt; /h2 & gt; & lt; h2 & gt; Title 3 & lt; /h2 & gt; & lt; /div & gt;

XPath to Select the Immediate Next & lt; h2 & gt; After & # 8220; Title 1 & # 8221;

//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:

2. Selecting All Following Siblings

When you need to retrieve or interact with multiple sibling constituent after a given reference.

Example HTML:

& lt; ul & gt; & lt; li & gt; Item 1 & lt; /li & gt; & lt; li & gt; Item 2 & lt; /li & gt; & lt; li & gt; Item 3 & lt; /li & gt; & lt; /ul & gt;

XPath to Select All & lt; li & gt; Elements After & # 8220; Item 1 & # 8221;

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

Use Case: Fetching all menu items that seem after a given one.

javascript let items = await driver.findElements (By.xpath (`` //li [schoolbook () ='Item 1 '] //following-sibling: :li '')); for (let detail 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 check input fields.

Example HTML:

& lt; label & gt; Username & lt; /label & gt; & lt; input type= '' textbook '' & gt; & lt; label & gt; Password & lt; /label & gt; & lt; input type= '' password '' & gt;

XPath to Select the Input Field After the & # 8220; Username & # 8221; 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 '');

Learn More:

4. Extracting Data from Tables

When you ask to bring a specific column value in a table based on a reference value.

Example HTML:

& lt; table & gt; & lt; tr & gt; & lt; td & gt; John & lt; /td & gt; & lt; td & gt; 25 & lt; /td & gt; & lt; /tr & gt; & lt; tr & gt; & lt; td & gt; Jane & lt; /td & gt; & lt; td & gt; 30 & lt; /td & gt; & lt; /tr & gt; & lt; /table & gt;

XPath to Select Age for & # 8220; John & # 8221;

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

Use Case: Extracting age dynamically for a specific gens.

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 repeat elements (e.g., section, divs) you need to place related ingredient.

Example HTML:

& lt; div & gt; & lt; h3 & gt; Section 1 & lt; /h3 & gt; & lt; p & gt; Description 1 & lt; /p & gt; & lt; /div & gt; & lt; div & gt; & lt; h3 & gt; Section 2 & lt; /h3 & gt; & lt; p & gt; Description 2 & lt; /p & gt; & lt; /div & gt;

XPath to Select the<p>After & # 8220; Section 1 & # 8221;

//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 [textbook () ='Section 1 '] //following-sibling: :p '')) .getText (); console.log (description);

Also Read:

How to Use Following-Sibling for Elements with Specific Text or Attributes

The following-sibling:: XPathaxis allows testers to select sibling constituent after a reference element within the same parent.

This technique is utilitarian to deal with dynamic table, tilt, variety, or nested elements where unmediated element choice isn & # 8217; t viable.

By combining following-sibling with text (), contains (), and property filters, you can precisely target the requisite constituent.

1. Using Following-Sibling with Specific Text

Select a paragraph & lt; p & gt; that follows an & lt; h2 & gt; lead with specific text.

HTML Structure:

& lt; h2 & gt; Product Name & lt; /h2 & gt; & lt; p & gt; Price: $ 100 & lt; /p & gt; & lt; p & gt; Availability: In Stock & lt; /p & gt;

XPath Expression:

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

This XPath selects the inaugural & lt; p & gt; that follows the & lt; h2 & gt; with text & # 8220; Product Name & # 8221;.

2. Using Following-Sibling with contains (text ()) for Partial Matches

Select a button that follows a & lt; div & gt; containing the schoolbook & # 8220; Checkout & # 8221;.

HTML Structure:

& lt; div & gt; Proceed to Checkout & lt; /div & gt; & lt; button & gt; Pay Now & lt; /button & gt;

XPath Expression:

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

This selects the & lt; button & gt; that follows the & lt; div & gt; containing & # 8220; Checkout & # 8221;, even if the textbook isn & # 8217; t an exact match.

3. Using Following-Sibling to Find an Element with a Specific Attribute

Select a & lt; span & gt; element that follows a & lt; label & gt; with the attribute for= & # 8217; email & # 8217;.

HTML Structure:

& lt; label for= '' e-mail '' & gt; Email Address & lt; /label & gt; & lt; span & gt; Invalid Email & lt; /span & gt;

XPath Expression:

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

This selects the & lt; span & gt; component with the class & # 8220; error-msg & # 8221; that follows the & lt; label & gt; for & # 8220; email & # 8221;.

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Read More:

Difference between Preceding-Sibling and Following-Sibling XPath axis.

The preceding-sibling and following-sibling XPath axes are used to pilot through sibling elements in the DOM.

The main difference is the traversal way:

XPath AxisDescriptionExample Selection
following-siblingSelects all sibling elements that look after the current nodeFinds next elements with the same parent.
preceding-siblingSelects all sibling elements that appear before the current node.Finds former elements with the like parent.

 

Also, there are some major deviation betweenfollowing-sibling and preceding-sibling, as shown below:

Featurefollowing-siblingpreceding-sibling
Traversal DirectionSelects elements after the credit node.Selects elements before the citation node.
Selection ScopeSelects only sibling elements that share the same parent.Selects only sibling elements that share the like parent.
Common Use CaseSelecting future elements (e.g., next signifier field, adjacent table row).Selecting previous elements (e.g., previous form field, previous table row).

Good Practices for using Following-Sibling XPath in Selenium

Using following-sibling XPathefficaciously in Selenium requires writing robust, maintainable, and efficient locator.

Also Read:

Below are the best practices to follow:

1. Use Specific Element Identifiers to Improve Accuracy

Always try to use an identifier (ID, form, text) in the base element before using following-sibling.

Avoid utilise generic tags like //div//following-sibling: :div, as they may return unintended result.

Example (Good XPath):

//h2 [textbook () ='Section Title '] //following-sibling: :p [1]

Example (Bad XPath & # 8211; Too Generic):

//div//following-sibling: :p

Also Read:

2. Use Indexing Carefully

The [1] index select merely the contiguous next sibling.

  • If selecting all siblings, avoid unnecessary indexing.
  • If indexing is necessary, ensure the page structure rest consistent.

Selecting the First Following Paragraph:

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

Selecting All Following Paragraphs:

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

3. Combine following-sibling with Other Attributes

Improve accuracy by combiningfollowing-siblingwith attributes like @ course, @ id, or contains (text ()).

Example: Select the initiatory paragraph after a drift with a specific class

//h2 [@ class='title '] //following-sibling: :p [1]

Example: Select the next input battlefield 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 inquiry.
  • Use By.id, By.className, or By.cssSelector when possible, as they are faster.

Example (Inefficient XPath & # 8211; Unnecessary Traversal):

// * [schoolbook () ='Username '] //following-sibling: :input

Example (Efficient XPath & # 8211; Direct Selection):

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

Mutual Challenges with Following-Sibling XPath and Solutions

Using following-sibling XPath in Selenium can be knock-down but comes with some challenge.

Below are common issues and result to control accurate element selection and effective test automation.

1. Multiple Duplicate Elements

When multiple sibling elements exist, following-sibling: :tagname may return more than one match, leading to unintended selections.

Example HTML:

& lt; div & gt; & lt; h2 & gt; Title 1 & lt; /h2 & gt; & lt; p & gt; Paragraph 1 & lt; /p & gt; & lt; p & gt; Paragraph 2 & lt; /p & gt; & lt; p & gt; Paragraph 3 & lt; /p & gt; & lt; /div & gt;

Wrong XPath (Selects All Paragraphs)

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

Solution: Use indexingto take a specific sibling.

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

This selects onlythe first paragraphafter the heading.

2. Dynamic Text or Attribute Changes

Elements with modify textbook or dynamic attribute might not twin exact XPath query.

Example HTML:

& lt; h2 & gt; Welcome, User123 & lt; /h2 & gt; & lt; p & gt; Dashboard Overview & lt; /p & gt;

Incorrect XPath (Fails if Username Changes)

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

Solution: Use contains ()for fond matching.

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

This works even if the username changes dynamically.

Also Read:

3. Invisible or Delayed Elements

Some elements may not be immediately available in the DOM due to or JavaScript rendering.

Example HTML (Delayed Rendering)

& lt; h2 & gt; Profile & lt; /h2 & gt; & lt; p & gt; User Info & lt; /p & gt;

Wrong XPath (Fails if Element is Not Rendered Yet)

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

Solution: Use Explicit Waitsin Selenium to look for the ingredient.

javascript let userInfo = await driver.wait (until.elementLocated (By.xpath (`` //h2 [text () ='Profile '] //following-sibling: :p '')), 5000);

This waits up to5 secondsfor the ingredient to appear.

Must Read:

4. Extra Whitespaces in Text Content

Some elements may contain extra space, causing XPath to fail.

Example HTML:

& lt; h2 & gt; Page Title & lt; /h2 & gt; & lt; p & gt; Content Here & lt; /p & gt;

Wrong XPath (Fails Due to Extra Spaces)

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

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

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

Works still if supernumerary spaces subsist.

5. Unstable DOM Structure

If the webpage structure alteration (e.g., extra & lt; div & gt; wrappers are added), XPath may break.

Example HTML (Before Update)

& lt; h2 & gt; Contact Us & lt; /h2 & gt; & lt; p & gt; Email: support @ example.com & lt; /p & gt;

Working XPath Before Update

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

Updated HTML (Extra Div Introduced)

& lt; h2 & gt; Contact Us & lt; /h2 & gt; & lt; div & gt; & lt; p & gt; Email: support @ example.com & lt; /p & gt; & lt; /div & gt;

Wrong XPath (Breaks Due to Additional & lt; div & gt;)

//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 & lt; div & gt; is innovate.

Why Run Selenium Tests on Existent Devices?

Testing on real devices ensures accurate, real-world results that can not replicate. Factors like browser behavior, meshing conditions, hardware performance, and real user interaction impact web applications, get testing on essential.

A cloud-based platform likeBrowserStack Automateprovides instantaneous access to 3,500+ real devices and browsers, eliminating the need for an in-house device lab. It enables seamless and across different OS, browser, and mobile device in.

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 & amp; OS Behavior: Ensures correct rendering, JavaScript execution, and UI consistency.
  • Existent Network Conditions: Tests performance under Wi-Fi, 4G, 5G, and slow networks.
  • Hardware Variability: Considers CPU, RAM, battery constraints, and existent device responsiveness.
  • Touch & amp; Gesture Support: Validates real interactions like swipe, pinch, and tap.
  • Real Sensor Testing: Ensures GPS, camera, microphone, and biometric authentication work right.
  • : Tests apps on Chrome, Safari, Edge, Firefox, and more.
  • Faster Test Execution: Supports Selenium,,, and for and automatise examination.
  • Seamless : 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

Many-sided

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 Seleniumenables efficient navigation through web elements, especially in case where factor lack unique dimension.

Using the following-sibling:: axis,testers can locate ingredient that appear after a reference element within the same parent, making it a valuable technique for deal dynamic tables, tilt, and structure substance.

While Following-Sibling XPath is a powerful locator scheme, it should be habituate strategically with other robust and maintainable techniques.

Tags

On This Page

54,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free