Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does //span[2] not select the second span in a document?

I have the following html:

<!doctype HTML>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Test</title>
</head>
<body>

<p>A <span>one</span></p>

<p>B <span>two</span></p>

<p>C <span>three</span></p>

<p>D <span>four</span></p>

</body>
</html>

Running the XPath //span[1] gets the first span. However //span[2] returns null:

 input: document.evaluate("//span[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
output: <span>​one​</span>​

 input: document.evaluate("//span[2]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
output: null

Why does this happen?

like image 212
Stuart K Avatar asked Jun 24 '26 20:06

Stuart K


2 Answers

the [2] has higher precedence as the //. You should read your original xpath query as:

//(span[2])

This means, it looks everywhere in the document for the second span element of the same parent element.

If you write (//span)[2] instead, it will look for span elements everywhere, and then select the second span.

like image 132
Elian Ebbing Avatar answered Jun 26 '26 11:06

Elian Ebbing


Because //span[1] refers to the first span element of the span's parent. There are actually 4 that meet this criteria (all 4). You only see one due to using .singleNodeValue

//span[2] is asking for spans that are the 2nd child of their parent.

Try it with this body to see

<body>
<p>A <span>one</span></p>
<p>B <span>two</span></p>
<p>C <span>three</span></p>
<p>D <span>four</span><span>five</span></p>
</body>
like image 33
RichardTheKiwi Avatar answered Jun 26 '26 13:06

RichardTheKiwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!