Playwright Locator vs ElementHandle

Profile picture for user arilio666

The playwright can support several methods of locating UI elements from the web page. It can be done using ElementHandle or by the Locator, which aids the search for DOM elements on a webpage.

Locator
page.locator("#Button").click();

ElementHandle 
page.$("#Button").click();

There are some differences between these element hunters.

Approach:

  • ElementHandle points to a specific DOM element on the page, while Locator captures the logic of how to fetch an element.
  • The problem with ElementHandle is that if it only points out a particular element and, shortly, the element of a specific area has some modifications, this can cause trouble and unexpected behavior.
const doIt = await page.$('text=cart');
// ...
await doIt.textContent();
await doIt.click();
  • However, with Locator, the exact text is fetched with the up-to-date DOM element.
const doIt = await page.getByText('cart');
// ...
await doIt.textContent();
await doIt.click();
  • So Locator identifies 'cart' text with ease than ElementHandle.

Garbage Collection:

  • When Locator is no longer found, there will be a timeout, and all commonly know this.
  • In ElementHandle, when the underlying DOM object is deleted, it is not disposed of by garbage collection until the handle is disposed of.

Reference:

  • ElementHandle refers to the same old DOM element given before, so doing operations with it can be easy.
  • The Locator is searched for on the web page every time it is used.
  • This can be troublesome for the Locator as it can cause a timeout.

Adaptability:

  • Locators are most often used and recommended because modern websites change dynamically frequently.
  • Using ElementHandle can be troublesome as it can point out that the elements no longer exist at the time of action.
  • Locator can find the proper objects at the time of action.

Conclusion:

Using Locator can be the recommended thing to do if we want to handle tests more dynamically.