Rayrun
← Back to Discord Forum

How do I get the underlying DOM object from a locator?

I'm using a CSS selector, but still getting locator objects.

Specifically, I want to walk through a list of checkboxes and verify whether each one is checked or not, as expected.

Then one of the elements has a following sibling ... just a div, and I'd like to verify whether it's present or not.

I know that locators have a builtin await-er, but that's not an issue in this case, as far as I can tell.

This thread is trying to answer question "How do I get the underlying DOM object from a locator?"

4 replies

assume you could evaluate returning a node, bet if needed could write it just as well/performant with locators and avoid all the hacky error prone way you are heading down...

bububu8615
bububu8615

So as I understand you want to skip the locator have following-sibling::div? If in that case you have to add filter({hasNot: page.locator("//following-siblings::div")}) or you can use css "~div"

How do I assert on element.checked ? I expect some of them to be checked and some not to be.

isChecked? But that is a different question from what you asked?

Answer

Retrieving DOM Elements with Playwright

In Playwright, you can use the evaluateHandle method to get the underlying DOM object from a locator. This method executes JavaScript code within the page context and retrieves a handle to the DOM element.

Here's how you can do it:

const locator = page.locator('your-locator');
const handle = await locator.evaluateHandle((element) => element);

Replace your-locator with your actual locator expression. The evaluateHandle method takes a function as its argument, which is executed in the browser's JavaScript environment. The function receives the matched element as its parameter and returns it.

Once you have the handle, you can perform various operations on it using Playwright's API. For example, you can interact with its properties or call methods on it.

Remember, when using evaluateHandle, Playwright automatically serializes and deserializes complex objects between Node.js and browser contexts. This means that even if your locator matches multiple elements, only their handles will be returned rather than their full representations.

So, with Playwright's evaluateHandle method and a locator expression, you can easily get handles to underlying DOM objects and perform further actions on them in your automation scripts.

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 luc@ray.run.