Last Updated: September 09, 2019
·
98.96K
· Andrew Stilliard

Javascript get element by xpath

Although its rare i'll use xpath, if you're ever testing it for web crawling etc you can just fire this in the browser console to log the element:

document.evaluate('XPATH HERE', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

So say you'd like to quickly grab some elements innerHTML:

document.evaluate('/html/body/div[4]/div[2]/div/div/div/div[3]/div/span[2]/span', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.innerHTML;

1 Response
Add your response

I joined coderwall just to say thank you. I had been trying to use the JQuery $x() function to aquire an element and although it would return it, the browser was not allowing me to access the innerHTML and innerTEXT variables."

over 1 year ago ·