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 Answer
Reset to default 16Look 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>
document.getElementByXpath
developer.mozilla.org/en-US/docs/Web/API/Document/evaluate – epascarello Commented Oct 28, 2021 at 12:58