5

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);
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
JustBeingHelpful
  • 18,332
  • 38
  • 160
  • 245

1 Answers1

6

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);
}
​
Alp
  • 29,274
  • 27
  • 120
  • 198
  • 1
    do you have any good references (links) with good examples for the different result types. I'm still trying to wrap my head around how they work. – JustBeingHelpful Apr 10 '12 at 19:31
  • 1
    This should give you a good start: [Introduction to using XPath in JavaScript](https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript) – Alp Apr 10 '12 at 19:32
  • That's the one I was reading. Haha! I thought that documentation was poorly written. They didn't have a complete set of good examples. – JustBeingHelpful Apr 10 '12 at 19:33