Make Selenium Easy

Selenium Interview Question 7 – How to Select Last Five Checkboxes

This question was recently asked in a Selenium group on Facebook.

Generally these types of question are asked frequently in Selenium. Select last N elements or only odd elements or only even elements or second last elements etc. Answer of all questions will be originated from same point.

In this post, I will explain selecting last five checkboxes using Selenium.

Consider below webpage:-

HTML Code:-

Requirement is to select last five checkboxes. There are two ways to achieve this:-

Approach 1:- Using iteration

Locate all element and start iterating with starting index as (total count-5) and end index as (count-1).

Approach 2: Using XPath methods named last() and position()

Write xpath to locate check boxes whose position is greater than 5th i.e. 6th, th, 8th, 9th and 10th. We can use position() and last() methods for this.

List lastFiveCheckboxes= driver.findElements(By.xpath(“//input[position() > last()-5]”));

last() will give last index i.e. 10 and position()>(10-5) will give checkboxes from 6th position.

Java Program:-


Total checkboxes found: 10
Total checkboxes found: 5

If you like above post and feel it is worth to share to reach it to maximum people, please do.


Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

1 thought on “Selenium Interview Question 7 – How to Select Last Five Checkboxes

  1. Hi. In second approach of this post, if we do have elements which do have input tag in their html other than check boxes, in that case we would not be able to find position of last 5 check boxes using the above code, am I right? Correct me If i am not getting the things.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.