XPath element/object is undefined when using document.evaluate

妖精的绣舞 提交于 2019-12-01 20:48:01

问题


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);

回答1:


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);
}
​


来源:https://stackoverflow.com/questions/10094891/xpath-element-object-is-undefined-when-using-document-evaluate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!