XPath element/object is undefined when using document.evaluate
-
30-05-2021 - |
题
How can I fix the regular JavaScript code so it doesn't say "undefined" and displays the value of the input field? The jQuery code works fine and displays the input field value correctly on the same page.
Regular JavaScript:
var obj = document.evaluate('//html/body/form/div[4]/label/input',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
alert(obj.value);
JQuery 1.7.1 code:
var obj = $('html > body > form > div:nth-child(4) > label > input');
alert(obj.value);
解决方案
document.evaluate()
returns an XPathResult. You can retrieve the element like this:
var obj = document.evaluate('//html/body/form/div[4]/label/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if(obj != null) {
alert(obj.value);
}
不隶属于 StackOverflow