How to Skip Elements in Xpath

H

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.

Mozilla

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

<ul>
    <li>Select option</li>
    <li>Linux</li>
    <li>Windows</li>
    <li>Mac</li>
</ul>

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.

//ul/li[position()>1]/text()
Result:
[“Linux”,”Windows”,”Mac”]

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:

//ul/li[position()<4]/text()
Result:
[“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()
Result:
[“Linux”,”Windows”]

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

Add Comment

By lovejeet

lovejeet

Get in touch

Quickly communicate covalent niche markets for maintainable sources. Collaboratively harness resource sucking experiences whereas cost effective meta-services.