Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath element/object is undefined when using document.evaluate

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);
like image 904
MacGyver Avatar asked Apr 10 '12 19:04

MacGyver


1 Answers

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);
}
​
like image 121
Alp Avatar answered Oct 17 '22 15:10

Alp