Playwright ElementHandle

Profile picture for user arilio666

ElementHandle is a way to represent the DOM element on the page and can be created with the page.$(selector, options).

However, the use of ElementHandle is not encouraged. Instead, locator objects are encouraged to be used.

Syntax:

page.$('id')
  • ElementHandle prevents DOM element from garbage collection unless the handle is disposed with jsHandle.dispose(). They are auto disposed of when their origin frame gets navigated.
  • ElementHandle can also be used as an argument on the page.$eval()
  • The main difference between the locator and ElementHandle is that ElementHandle points to a particular element. In contrast, on the other end, the locator captures the logic of how to retrieve an element.

ElementHandle $:

const {test, expect} = require('@playwright/test');
test('ElementHandle', async ({page})=> 
{

await page.goto("https://www.programsbuzz.com/user/login");
const text = await page.$('div.description')
 console.log(await text.textContent())
});

Let us try to extract the text using ElementHandle here.

  • We can see that the ElementHandle doesn't care about the other text below the password and fetches the particular element found in the first place.
  • ElementHandle points to a particular DOM element on the page. Later, when that element is modified or used by react to render a different component, the handle will still latch on to that same DOM element.
  • This causes unexpected behavior.

Locator:

const {test, expect} = require('@playwright/test');
test('ElementHandle', async ({page})=> 
{

await page.goto("https://www.programsbuzz.com/user/login");
const text = await page.locator('div.description')
 console.log(await text.textContent())
});
  • The same logic failed here since the DOM fetched two elements' presence.

  • We can witness here that it resolved to two elements, and that's why locator objects are used to write logic on how to retrieve an element.

That's why Locators are the ideal object to be used instead of ElementHandle.