I have a HTML like this:
<div>
<div>Internal Description</div>
<app-rich-text-editor>
<div data-testid="rich-text-editor">
</div>
</app-rich-text-editor>
</div>
<div>
<div>External Description</div>
<app-rich-text-editor>
<div data-testid="rich-text-editor">
</div>
</app-rich-text-editor>
</div>
If I locate the div with
await page.getByTestId('rich-text-editor')
I get both divs. The difference between them are the text 'Internal Description' and 'External Description'. How to locate the first div with data-testid="rich-text-editor" and parent-parallel <div>Internal Description</div>?
You can work top-down:
<div>by text+CSS selector to grab the next<app-rich-text-editor>siblinggetByTestIdfunction to select by[data-testid="rich-text-editor"].It's also possible to use the attribute child selector since you're in CSS selector context anyway:
That said, if you're testing rather than scraping, using "heavy" selectors and CSS often might be a code smell. Consider adding specific test ids to the top-level container
<div>elements or using additional properties and structures that may be in your markup to keep your locators simple and avoid CSS selectors.It may also be possible to select based on layout, depending on your use case (but this is not always reliable, so proceed with caution).