Tengo un código muy básico. Simplemente cambia el estilo del botón al hacer clic. Funciona bien cuando se usa getElementById pero quiero hacerlo de la manera XPATH . Soy nuevo en JavaScript. ¿Qué estoy haciendo mal y cómo puedo lograr esto?
El código:
<!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>Mire 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>