5

I have a very basic code. It simply changes the style of the button on click. It works fine when used getElementById but I wanna do it the XPATH way. I'm new to JavaScript. What I'm doing wrong and how can I achieve this?

The code:

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to change the layout of this paragraph</p>

<button onclick="myFunction()">Click Me!</button>

<script>
function myFunction() {
  let x = document.getElementByXpath("//html[1]/body[1]/button[1]");
  x.style.fontSize = "25px"; 
  x.style.color = "red"; 
}
</script>

</body>
</html>

Abhay Salvi
  • 890
  • 3
  • 15
  • 39
  • 1
    there is no `document.getElementByXpath` https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate – epascarello Oct 28 '21 at 12:58
  • And there is a lot better ways to do this without XPATH. – epascarello Oct 28 '21 at 12:59
  • Does this answer your question? [Is there a way to get element by XPath using JavaScript in Selenium WebDriver?](https://stackoverflow.com/questions/10596417/is-there-a-way-to-get-element-by-xpath-using-javascript-in-selenium-webdriver) – Asalan Dec 10 '22 at 23:54

1 Answers1

13

Look at document.evaluate()

function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

function myFunction() {
  let x = getElementByXpath("//html[1]/body[1]/button[1]");
  x.style.fontSize = "25px"; 
  x.style.color = "red"; 
}
<p id="demo">Click the button to change the layout of this paragraph</p>

<button onclick="myFunction()">Click Me!</button>
Alan Yu
  • 1,462
  • 12
  • 21
  • Hey! Thanks for this. It worked! However, I've a question tho. What does `.singleNodeValue` do? Can you explain the code? – Abhay Salvi Oct 28 '21 at 13:10
  • 1
    @Abhaysalvi [singleNodeValue](https://developer.mozilla.org/en-US/docs/Web/API/XPathResult/singleNodeValue) – Alan Yu Oct 28 '21 at 13:23