Why does // span [2] not select the second range in the 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 XPath //span[1]gets its first span. However, it //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 is this happening?

+3
source share
2 answers

[2]has a higher priority than //. You should read your original xpath request as:

//(span[2])

This means that it appears throughout the document for the second span of the same parent.

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

+6
source

//span[1] span span. 4 ( 4). - .singleNodeValue

//span[2] , .

<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>
+2

Source: https://habr.com/ru/post/1787409/


All Articles