Search code examples
typescriptcss-selectorsplaywrightplaywright-typescript

difference between locating an element in two different ways in Playwright


await page.locator('nb-calendar-pageable-navigation [data-name="chevron-right]').click();
await page.locator('nb-calendar-pageable-navigation').locator('[data-name="chevron-right]').click();

I'm new to Playwright.

What is the difference between these two approaches of finding a specific element with Playwright (ts)? Are there any preferences for using one or another?

Tried to use them for the same case, and the outcome is the same


Solution

  • Looking at it from the reusability and maintenance perspective , would choose second approach :

    1. Modularity: As a named variable it would bring modularity in the code as it can be re-used in multiple places with the combination of other locators/sub locators as well.

    2. Ease of maintenance: if one part changes , it can be easily modified without affecting the other as may be the other part is used with other sub locators as well.

    3. Flexibility: This way you can define lot of partial locators which can be composed together on a need basis.

    I am using this way on a very large scale in a project where I have thousands of partial locators which are combined in different ways in different places on need basis.