[Web Automation] How to get an element value or interact with an element by XPath just using JavaScript

Sometimes you may not want to use Get Value or Click Element nodes connecting them one by one but instead you may want to use just one Run Script node to do multiple things.

image

But you also want to use an XPath of the elements. This code block below helps you to do just that:

document.evaluate("YOUR_XPATH_HERE", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

So to get the value of an element with xpath //h1[@class=“news-title”] you can use this code block

var elem = document.evaluate("//h1[@class='news-title']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

return elem.value;

or to click a button with XPath like //button[@id=‘submit’] you can use this code block

var elem = document.evaluate("//button[@id='submit']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

elem.click;

This is how it looks like in a Run Script node

2 Likes