1. XPATH functions and advanced predicates
Besides axes, steps, and predicates, another building block of the XPATH notation are functions.
With these, querying a website for specific elements becomes even easier.
2. The position() function
One of the most important - if not the most important - functions is position(). With it you can reference the current position of each element in your path selection, and then use that in a predicate.
For example, this predicate here only selects the li element at the second position within the ol element. That's similar to what the nth-child pseudoclass in CSS does.
3. More operators for the position() function
However, that's not the whole story. You can use other so-called operators like the less-than-sign in predicates.
This path, for example, selects all the li nodes with a position of less than three. That's the first two elements.
4. More operators for the position() function
There's also the unequal operator, denoted by an exclamation mark followed by the equal sign.
This selects all the elements that have not position three. That's something you certainly can't do with CSS selectors.
5. Combining predicates
What's even more awesome: You can also combine several conditions within a predicate, either with the "and" operator or with the "or" operator. In this case here, the "and" operator is used to combine two conditions that must both hold. First, the li element should not be at position 3. Second, it should have the "blue" class.
This holds for the first and the fifth element in this case. The second and fourth elements are not returned because they don't have the "blue" class.
If we were to use the "or" operator instead, all the elements would be selected, because the first condition is true for all the elements except the third, and the second condition is true for the third element. So either of both conditions holds for all elements.
6. The count() function
Another helpful function that is used slightly differently is the count() function. In this example, we have two different ordered lists with a differing number of children.
With the count() function, we can select the ol nodes that have a certain amount of children, for example, two. Note that the predicate is applied directly after the ol step in the path. Also, you need to specify the type of children you want to count. In this case, these are the li nodes.
Needless to say that the count() function can also be combined with several different operators, like the greater-than operator in this case, which selects only the first ol element here.
7. Let's try out some functions!
Okay, let's have a look at some functions in practice.