Is there a way to use JavaScript to get an element by XPath in Selenium WebDriver?

Building on that, yes, It’s definitely doable, but a heads-up—XPath can be fragile if your page structure changes often. So while the JS snippet below is handy:

document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue

you’d wrap that inside Selenium’s executeScript() to grab your element. But if you can, try to use more stable locators like data-testid or ARIA attributes, especially if you have some control over the application’s codebase. Keeps your tests less flaky.