<p>I'm using this XPath to get the value of a field:</p>

<pre class="lang-none prettyprint-override"><code>//input[@type="hidden"][@name="val"]/@value
</code></pre>

<p>I get several results, but I only want the first. Using</p>

<pre class="lang-none prettyprint-override"><code>//input[@type="hidden"][@name="val"]/@value[1]
</code></pre>

<p>Doesn't work. Once I have this, how do I pick up the value in Greasemonkey? I am trying things like:</p>

<pre><code>alert("val " + val.snapshotItem);
</code></pre>

<p>But I think that's for the node, rather than the string.</p>

For the XPath, try:
```
//input[@type="hidden" and @name="val" and position() = 1]/@value
```
For use in a GreaseMonkey script, do something like this:
```
```
var result = document.evaluate(
  "//input[@type='hidden' and @name='var' and position()=1]/@value",
  document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);

var hiddenval = result.snapshotItem(0);

if (hiddenval)
  alert("Found: " + hiddenval.nodeValue);  
else
  alert("Not found.");
```
```
Strictly speaking: Using
```
"position()=1"
```
in the XPath filter is not absolutely necessary, because only the first returned result is going to be used anyway (via
```
snapshotItem(0)
```
). But why build a larger result set than you really need.
EDIT: Using an XPath result of the
```
ORDERED_NODE_SNAPSHOT_TYPE
```
type makes sure you get the nodes in
document order
. That means the first node of the result will also be the first node in the document.