How to Skip Elements in Xpath


Recently I came across a situation where I had to skip the first li tag from a list of li tags. This is where the position() function in xpath came to my help. Using the position() function, you can specify the number of elements you want to skip both from the beginning or ending of a list of elements. Even a combination of both.

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


The post will be a guide on how to use the position() function in xpath to skip elements or nodes.

Here is an example html. We are going to demonstrate the position() function on this

    <li>Select option</li>

Skip Elements from the Beginning in Xpath

So, from the above html, I can skip the first li element and get the value of the remaining list elements using the below xpath. 

Note: In Xpath the position numbering starts from 1.




Skip Elements from the Ending in Xpath

If you need to skip elements from the end, you can simply change the greater than symbol to less than and substitute the position value with the number of the element from the end. For example:



[“Select option”,“Linux”,”Windows”]

The above xpath will select all the li elements from the example html except the last one. 

Skip Elements from the Beginning and Ending in Xpath

You can even skip elements both from the starting and ending of a list of elements using the position() function. For example, you can use the below xpath to skip the one element from the beginning and one element from the end.

//ul/li[position()>1 and position()<4]/text()



As you can see the position() function comes very handy when you need to skip elements or nodes from the beginning, ending or both beginning and ending. If you have some queries or suggestions about the position() function in xpath. Do let me know in the comments below.

About the author


Lovejeet is a Proud Geek and tech. enthusiast, who is ardent to learn more about the technology that surrounds us. He loves to tinker around with his gadgets and when he find something new and exciting, he shares it with you on this blog. Last but not the least he is a true gamer by heart. Connect with him on and Twitter

Add comment

By Lovejeet