开发者

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: documen开发者_如何学运维t.evaluate("//span[2]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
output: null

Why does this happen?


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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜