Learn About Less Talked & Used XPath Function – position()

XPath 1 provides a powerful function named “position()” . Before we move further, let’s get in to a scenario where we need this.

Consider below web page. We have six different tab headers which are actually country capital names. I used W3School reference to get below html design.

If I ask you to give me Xpath for Nth indexed tab header i.e. 2nd Header or 4th header. Probably you will write XPath as below :-

(//button[@class=’tablink’])[2] – For 2nd indexed

(//button[@class=’tablink’])[4] – For 4th indexed

Note:- In XPath index starts from one (1) not from zero as we see in programming languages.

Now if I ask you to:-

  1. Give me a XPath which locates tab headers from 2nd to 4th index?
  2. Give me a XPath which locates 2nd and 4th indexed tab headers together?
  3. Give me a XPath which locates tab headers which are before 5th index?
  4. Give me a XPath which locates tab header which are after 2nd index?

Now here you need to use XPath function called “function()”.

The position function returns a number equal to the context position from the expression evaluation context.

We can replace index with position as below:-

(//button[@class=’tablink’])[2] -> //button[@class=’tablink’][position()=2]

(//button[@class=’tablink’])[4] -> //button[@class=’tablink’][position()=4]

We can use conditional operator like greater than , less than , greater than and equal to, less than and equal to and not equal to etc. Even we can use logical operator like AND & OR with it.

To get all headers from 3rd index onward i.e 4th, 5th and 6th

//button[@class=’tablink’][position()>3]

To get all headers from 3rd index including i.e 3rd, 4th, 5th and 6th

//button[@class=’tablink’][position()>=3]

To get all headers before 5th index i.e 1st, 2nd, 3rd and 4th

//button[@class=’tablink’][position()