XPath: How to select node with some attribute by index?

This is a FAQ.

In XPath the [] operator has a higher precedence (binds stronger) than the // pseudo-operator.

Because of this, the expression:

//div[@class="test"][2]

selects all div elements whose class attribute is “test” and who (the div elements) are the second such div child of their parent. This is not what you want.

Use:

(//div[@class="test"])[2]

Leave a Comment