Getting Stale element exception when iterating over a dropdown in Selenium



  • List<WebElement> dropdownlist = driver.findElements(By.xpath("//*
    [contains(@class,'mat-option ng-star-inserted')]//span"));
    int count = dropdownlist.size();
    for (int j=0; j<=dropdownlist.size(); j++) 
    {               
            dropdownlist.get(j).click();  
    } 
    

    My first dropdown list item gets selected and second one is not getting clicked.



  • A stale element exception occurs when selenium element is no longer valid. It can be caused when your DOM refreshed after you resolved your element.

    • I suggest you observe what happens after you click on an option of your dropdown.
    • Try the code below: (only work around check behavior after element click, for proper solution)

      int count = dropdownlist.size();                     
      
             for (int j=1; j<=dropdownlist.size(); j++)
               {              
                  WebElement opt = driver.findElements(By.xpath("(//*[contains(@class,'mat-option ng-star-inserted')]//span)["+j+"]"));
                  opt.click();  
               } 
      


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2