How can you access a sibling element in Playwright using C# syntax?

How can you access a sibling element in Playwright using C# syntax?

When working with Playwright, you may encounter situations where you need to select a sibling element, such as accessing the next <span> following another within the same parent. For example, if you have two sibling <span> elements — one showing a label and the other showing dynamic content — you might want to retrieve the second element’s value.

In JavaScript, you can use a selector like ':text("Status:") + span', but in C#, the syntax differs slightly. You can achieve the same behavior by combining XPath or CSS sibling selectors. For example:

var secondSpan = Page.Locator("//span[text()='Status:']/following-sibling::span");

This approach uses XPath to locate the span with the text Status: and then accesses its immediate sibling, which is useful for Playwright next sibling element selection in C#.

Having worked with UI automation for a few years now, I’ve found that the most reliable way in this kind of scenario is XPath.”

In Playwright C# sibling element lookups, the cleanest approach is often XPath. You can directly jump from a known label to its sibling like this:

var sibling = Page.Locator("//span[text()='Status:']/following-sibling::span");

This grabs the <span> containing Status: and then selects the next sibling <span> under the same parent. Really handy when you want to scrape dynamic values right beside static labels.

I’ve run into this pattern a bunch of times while building test suites over the years, and here’s a bit more clarity.

To enhance what Akansha said in Playwright C# sibling element handling, you can use both XPath and CSS. Personally, I lean toward XPath for readability:

await Page.Locator("//span[text()='Status:']/following-sibling::span").TextContentAsync();

It’s especially useful when UI layouts pair labels with values (like status, price, version, etc.). XPath makes that relationship very explicit.

From my experience maintaining large automation frameworks, keeping selectors modular is key.

If you’d like an alternative while still handling a Playwright C# sibling element, you can combine CSS with a scoped XPath inside chained locators:

var label = Page.Locator("span:has-text('Status:')");
var sibling = label.Locator("xpath=following-sibling::span");

This keeps the “find the label” and “find its sibling” steps separate, which makes your code cleaner, reusable, and easier to debug when UI changes start creeping in.