Search code examples
javaselectseleniumindexinghtml.dropdownlistfor

Selenium/Java: get index/position of currently selected option in a dropdown menu


How do get the index of the currently selected option in a dropdown menu in Selenium? Getting the text label for it is easy

String searchString = select.getFirstSelectedOption().getText();

It is also easy to select the n-th element

select.selectByIndex(25);

But I want to know that the currently selected item's index is 25. When I know that I want to log the value and then select next by index.


Solution

  • I have used the below html code snippet of dropdown:-

    <select name="Students">
    <option value="student1">student1</option>
    <option value="student2">student2</option>
    <option value="student3">student3</option>
    <option value="student4">student4</option>
    </select>
    

    Below is the code for selecting from the dropdown and then getting the index of the option selected:-

        Select sel = new Select(driver.findElement(By.xpath("//select[@name='Students']")));
    
        sel.selectByVisibleText("student4");
    
        List<WebElement> list = sel.getOptions();
    
        for(int i=0;i<list.size();i++){
            if(list.get(i).getText().equals(sel.getFirstSelectedOption().getText())){
                System.out.println("The index of the selected option is: "+i);
                break;
                }
        }
    

    Note:- Output will be "3", as the index starts from "0".