如何在 JavaScript 中通过 XPATH 获取元素?

Abh*_*lvi 5 html javascript xpath dom

我有一个非常基本的代码。它只是更改单击时按钮的样式。使用时效果很好,getElementById但我想这样做XPATH。我是 JavaScript 新手。我做错了什么以及如何实现这一目标?

代码:

<!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>

Run Code Online (Sandbox Code Playgroud)

Ale*_* Yu 13

查看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"; 
}
Run Code Online (Sandbox Code Playgroud)
<p id="demo">Click the button to change the layout of this paragraph</p>

<button onclick="myFunction()">Click Me!</button>
Run Code Online (Sandbox Code Playgroud)