What is the difference between ElementHandle and Locator in Playwright?


Understanding ElementHandle in Playwright

ElementHandle is a class in Playwright that signifies an in-page DOM element. You can create it using the page.$() method. However, it's generally discouraged to use ElementHandle. Instead, you should use Locator objects and web-first assertions.

const elementHandle = await page.$('#my-element');

The reason is that ElementHandle can prevent the DOM element from garbage collection unless you dispose of the handle with jsHandle.dispose(). This can lead to unexpected behaviors if the element changes text or is used by React to render a different component.

ElementHandle vs Locator

ElementHandle points to a specific element, while Locator captures the logic of how to retrieve an element. With Locator, every time the element is used, an up-to-date DOM element is located on the page using the selector.

const locator = page.locator('#my-element');

If you use ElementHandle and the DOM element changes text or gets replaced, your handle will still point to the same DOM element, which can cause unexpected behavior.

Using ElementHandles

If you decide to use ElementHandles, they can be used as arguments in page.$eval() and page.evaluate() methods. There are several methods available for working with elements such as $(), $$(), $eval(), $$eval(), click().

const result = await elementHandle.$eval('.child', (child) => child.textContent);

In conclusion, it's best practice not to use ElementHandles unless necessary. Instead, consider using Locators which capture logic on how to retrieve specific elements from a webpage. This ensures you always have up-to-date information about what's happening on your site.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.