Home > front end >  How to get Element by XPATH in JavaScript?
How to get Element by XPATH in JavaScript?

Time:10-29

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>

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related