1

This is the DOM structure:

<div class="row">
  <label class="left">foo</label>
  <label class="right">bar</label>
  <label class="left">baz</label>
  <label class="right">qux</label>
  <label class="left">abc</label>         <!-- I know this -->
  <label class="right">123</label>        <!-- I want this -->
</div>

I want the immediate sibling of "abc", i.e. "123".

I tried these, but both time out:

await page.Locator(".row").GetByText("abc").Locator("+ .right").InnerText();

await page.Locator(".row").Locator(":right-of(:text('abc'))").InnerTextAsync();

I also tried using ElementHandle, without success.

How can I get the immediate sibling of the locator above?

UPDATE

As you can see, I already tried the special Playwright syntax "right-of" but it times out. So this is not a dupe of the linked question, which does not work in this case.

lonix
  • 14,255
  • 23
  • 85
  • 176
  • Does this answer your question? [Access to Sibling element in Playwright](https://stackoverflow.com/questions/73240528/access-to-sibling-element-in-playwright) – ggorlen Apr 28 '23 at 23:23
  • @ggorlen Thanks, no it doesn't help. As you can see above I tried that but it does not return the locator. I don't understand why this fails. – lonix Apr 28 '23 at 23:25

3 Answers3

0

I don't have a testing environment for the DOM so I'm spit balling a little. Does this work?

const loc = page.locator(':text("abc") + label').textContent();

I am going off the contents of this discussion in the github

I have not had good experience using a sibling selector in the latter parts of a chained locator. In my experience the + operator works best when part of other existing css locators rather than as part of a chain.

Arucious
  • 1
  • 1
0

following-sibling is the simplest direct way to do it.

This is something which directly can be handled on xpath level so no need to find an feature on playwright level to keep things simple.

You may use the direct following-sibling xpath like below:

//div[@class="row"]//label[contains(.,"abc")]/following-sibling::label[1]
Vishal Aggarwal
  • 1,929
  • 1
  • 13
  • 23
0

If you need to get exactly the Locator from the current Locator, then this solution may be suitable (in C#)

var nextSibling = await currentLocator.EvaluateHandleAsync("el => el.nextElementSibling");
var nextSiblingLocator = page.Locator("xpath=/html" + await nextSibling.EvaluateAsync<string>("el => el.outerHTML"));
ART webSD
  • 1
  • 1