Search code examples
javascripthtmltypescriptdomplaywright

How to work out if two different selectors point to the same element on a page?


Given the following page

<div id="something">
    <div id="selected">
    </div>
</div>

In playwright I have two selectors like this..

selectorA = "#something >> div >> nth=1";
selectorB = "#selected";

These two selectors point to the same element on the page. How can I compare the two selectors / locators to figure out if they are pointing to the same element or not?


Solution

  • I found out how to do it.

    async function compareLocators(firstLocator: Locator, secondLocator: Locator): Promise<boolean> {
        const firstHandle = await firstLocator.elementHandle();
        const secondHandle = await secondLocator.elementHandle();
        return firstLocator.page().evaluate(
            compare => compare.left.isEqualNode(compare.right),
            { left: firstHandle, right: secondHandle }
        );
    }
    

    Now you can feed this function two locators and it returns true/false if they point to the same locator.