最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to get Element by XPATH in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

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>

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>

Share Improve this question asked Oct 28, 2021 at 12:54 Abhay SalviAbhay Salvi 1,1193 gold badges17 silver badges47 bronze badges 3
  • 1 there is no document.getElementByXpath developer.mozilla.org/en-US/docs/Web/API/Document/evaluate – epascarello Commented Oct 28, 2021 at 12:58
  • And there is a lot better ways to do this without XPATH. – epascarello Commented Oct 28, 2021 at 12:59
  • Does this answer your question? Is there a way to get element by XPath using JavaScript in Selenium WebDriver? – Asalan Commented Dec 10, 2022 at 23:54
Add a comment  | 

1 Answer 1

Reset to default 16

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>

发布评论

评论列表(0)

  1. 暂无评论