Xpath select n-th node

I have such XML

<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 nth div where the class is "foo"?

I would select all foos using //div[@class="yay"/div[@class="foo"]

If I want to choose foo # 3, how to do it? Sort of:

//div[@class="yay"/div[@class="foo"][3] ?

+6
source share
2 answers

This is one of the most frequently asked questions in XPath .

Using

 (//div[@class="yay"]/div[@class="foo"])[3] 

Explanation

The XPath pseudo-operator // has a lower priority (priority) than the [] operator.

Thus

 //div[@class="yay"]/div[@class="foo"][3] 

means

Select each div whose class attribute is set to "foo" and that ( div ) is the third such child of its parent div .

If there are several parent div elements that have three or more such child elements, then all 3 children are selected.

As with many expression languages, the way to override the built-in priority is to use parentheses .

+24
source

This works for me, so you are right, //div/div[@class="foo"][2] or do you want to select, for example, element number 3 under "yay" and see if it has "foo"?

0
source

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


All Articles