An HTML page is essentially a hierarchy of nested nodes. For example, I might have a panel that displays a dialog containing a form, and within that form, a confirmation button.
When locating this button using Playwright, I could create a filter cascade to locate the button at the end of the node hierarchy. Alternatively, I could select the button directly without needing to know that it is nested within a form, which is inside a dialog, and so on.
Which approach should I use? Should I ensure the button's location by filtering through nodes, or should I keep it simple and select it directly?
What are the advantages of each one?
Playwright recommends using Locators. For instance you filter through your nodes, a simple change in the DOM can break your path. By using locators it will be the easiest way to address you button directly.
When you would like to locate an element which exists more than one but you know some criteria to narrow down its position you can use filter()
filtering
You can chain you locators as well.
Note that all methods that create a locator, such as page.getByLabel(), are also available on the Locator and FrameLocator classes, so you can chain them and iteratively narrow down your locator.
However, avoid using css
or xpath
and use them only when necessary. Especially xpath
can easily be broken.
In your case, you have more than one form (dialog) and each form has the button Confirmation
then I would locate the form and attach the button to it. e.g. getByRole('dialog').getByRole('button', {name: 'Confirmation'})