I have a XML like this
<div class="yay">
<div class="foo"></div>
<div class="foo"></div>
<div class="bar"></div>
<div class="foo"></div>
<div class="bar"></div>
<div class="foo"></div>
</div>
Is there a way to select the n-nth div where class is "foo"?
I'd select all foos with //div[@class="yay"/div[@class="foo"]
If I want to select foo #3 how do I do that? Something like:
//div[@class="yay"/div[@class="foo"][3]
?
In case we need to identify nth element we can achieve this by the ways listed below. position() method in xpath. Suppose we have two edit boxes in a page with similar xpath and we want to identify the first element, then we need to add the position()=1.
For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.
The key part of this XPath is *[1] , which will select the node value of the first child of Department . If you need the name of the node, then you will want to use this... Save this answer.
0 votes. Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.
This is one of the most FAQ in XPath.
Use:
(//div[@class="yay"]/div[@class="foo"])[3]
Explanation:
The XPath pseudo-operator //
has lower precedence (priority) that the []
operator.
Thus
//div[@class="yay"]/div[@class="foo"][3]
means:
Select every div
whose class
attribute has the value "foo"
and that (the div
) is the third such div
child of its parent.
If there are more than one parent div
elements that have three or more such children, then all of the 3rd children are selected.
As with many expression languages, the way to override built-in priority is to use parenthesis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With