XPath element / object undefined when using document.evaluate

How can I fix regular JavaScript code so that it doesn't say “undefined” and displays the value of the input field? JQuery code works fine and correctly displays the value of an input field on the same page.

Normal 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);
+3
source share
1 answer

document.evaluate()returns XPathResult. You can get the item as follows:

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);
}
+5
source

All Articles