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

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

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.

Selenium Interview Question 7 – How to Select Last Five Checkboxes

by Amod Mahajan time to read: 2 min
%d bloggers like this: