Search code examples
playwright

How Can I Select *Only* Direct Descendents?


Let's say you have a basic Playwright locator:

const locator = page.locator('.foo');

Now, you want to get just the <div> children of that locator ... not the grandchildren, great-grandchildren, etc. ... just the direct children.

You might naively try:

locator.locator('div');

... but that gets grandchildren and other descendants also. You might also try using the CSS direct descendant selector:

locator.locator('>div');

... but that also gets the grandchildren and other descendants.

Is there any way to get only the immediate/direct children of a locator?


Solution

  • You actually nailed it. '>div' will get you direct descendants.

    locator.locator('>div');
    

    For reference, here's the docs for locator.locator().