Rayrun
← Back to Discord Forum

Return `HTMLElement` from `await element.evaluate(..)` returning `undefined`

As the title says, I am trying to extract the target DOM element from a page.locator(<elemt>) value, to access stuff like the .children and .style , but the .evaluate(..) always returns undefined.

Is there a way to get this to work ?

Executing methods and logic inside the .evaluate using currying works fine, but even then, the return <something> always returns undefined.

This thread is trying to answer question "How can I get the '.evaluate(..)' method to return the target DOM element instead of 'undefined'?"

0 replies

Answer

Returning DOM Elements with Playwright's .evaluate(..) Method

If you're trying to return a DOM element with Playwright's .evaluate(..) method and getting undefined, it's because the function is returning a non-serializable value. But don't worry, there's a way around this!

Use frame.evaluateHandle()

Instead of frame.evaluate(), use frame.evaluateHandle(). This method returns a JSHandle, which represents the DOM element you're targeting.

Here's how you can do it:

const handle = await frame.evaluateHandle(() => {
  const targetElement = document.querySelector('.target-element');
  return targetElement;
});

In this code, document.querySelector('.target-element') selects the DOM element you want. The function then returns this element as a JSHandle.

Interact with the JSHandle

Now that you have a JSHandle, you can interact with it. For example, you can click on it:

await handle.click();

And that's it! You're now returning and interacting with DOM elements using Playwright's .evaluate(..) method. Just remember to ensure your JavaScript code is executed in a way that syncs with page actions and asynchronous operations.

For more tips on efficient Playwright test scripts, check out this blog post.

Related Discord Threads

TwitterGitHubLinkedIn
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 [email protected].