Home > Back-end >  Playwright - nested locator calls
Playwright - nested locator calls

Time:03-09

I have a structure like this I am trying to test:

<div custom-id=a>
  <div custom-id=b>
    <h1>one</h1>
  </div>
  <div custom-id=b>
    <h1>two</h1>
  </div>
</div>
<div custom-id=a>
  <div custom-id=b>
    <h1>three</h1>
  </div>
  <div custom-id=b>
    <h1>four</h1>
  </div>
</div>

I'd like to query it in two parts. First, get back all the custom-id=a nodes, then for each of those, get back all the custom-id=b nodes.

Based on previous questions I have asked, I was under the impression something like this would work:

const aNodes = await this.page.locator("custom-id=a");

for (let aNode in aNodes) {
  const bNodes = await aNode.evaluate(node =>
    Array.from(node.querySelectorAll('custom-id="b"')));
}

But when I try this, the IDE linter is telling me that aNode is a string. I guess I expected that aNodes would be an array of something I could again query.

My apologies if you have already answered questions from me along these lines. I am struggling to grasp some basics here.

CodePudding user response:

A locator is not iterable per se. But you can use the count function to get the elements count and then nth to get one element at a time:

const aNodes = await this.page.locator("custom-id=a");
const count = await aNodes.count;
for (let i = 0; i < count;   i) {
  const bNodes = await aNodes.nth(i).evaluate(node =>
    Array.from(node.querySelectorAll('custom-id="b"')));
}
  • Related