lonix
lonix

Reputation: 20947

Get immediate sibling of locator using PlayWright

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.

Upvotes: 5

Views: 7454

Answers (3)

ART webSD
ART webSD

Reputation: 19

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

Upvotes: 2

Vishal Aggarwal
Vishal Aggarwal

Reputation: 4207

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]

Upvotes: 3

Arucious
Arucious

Reputation: 7

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.

Upvotes: -1

Related Questions