-1

I am trying to iterate between all the options of a drop down and it works fine with the first option. After second option, I get stale Element Exception.

Below is the trace:

org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

Below is my code:

WebElement element = login.clickonCustomer();
        Select select = new Select(element);
        List<WebElement> listofelements = select.getOptions();
        for (int i = 1; i < listofelements.size(); i++) {
            String elementText = listofelements.get(i).getText();
            System.out.println(elementText);
            select.selectByVisibleText(elementText);
            login.ClickonLogin().click();
            Thread.sleep(3000);
            Accounts.clickonLogout().click();

        }
    }
Graham
  • 7,431
  • 18
  • 59
  • 84
  • Possible duplicate of [Getting StaleElementReferenceException while trying print the link names](https://stackoverflow.com/questions/44970712/getting-staleelementreferenceexception-while-trying-print-the-link-names) – undetected Selenium Feb 17 '18 at 09:04

2 Answers2

0

Got the solution.

   `element = login.customer();
    Select select = new Select(element);
    List<WebElement> listofelements = select.getOptions();
    // iterate through each and every option in the drop down
    for (int j = 1; j < listofelements.size(); j++) {
        Thread.sleep(3000);
        login.customer().click();
        String elementText = listofelements.get(j).getText();
        select.selectByVisibleText(elementText);
        login.loginbutton().click();
        Thread.sleep(3000);
        Assert.assertEquals(accounts.customername().getText(), elementText);
        accounts.logout().click();
        element = login.customer();
        select = new Select(element);
        listofelements = select.getOptions();
        }`
-1

try enclosing the code in try catch block.

  try
    {
        //your code to execute
    }
    catch(StateElementException e)
    {
   //enter the code that causes stale element exception
    }