简体   繁体   English

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

[英]How to get Element by XPATH in JavaScript?

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.使用getElementById时效果很好,但我想用XPATH方式。 I'm new to JavaScript.我是 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>

Look at document.evaluate()查看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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM