0

Hope someone can help me. I have the following code and I am getting the Exception thrown: 'OpenQA.Selenium.StaleElementReferenceException'

IList<IWebElement> WeekDays = Chromedriver.FindElements(By.XPath("//td[@class='dxeCalendarDay']"));

foreach (IWebElement Days in WeekDays)
{
    string WeekDaysResults = Days.Text;

    if(string.IsNullOrEmpty(WeekDaysResults))
    {
        //Do Nothing
    }
    else
    {
        if(WeekDaysResults == FirstDayOfCurrentMonth)
        {
            Days.Click();
            Debug.WriteLine("Week Days: " + WeekDaysResults);
        }        
    }
}

I'm getting the exception on this code string WeekDaysResults = Days.Text;

The error:

OpenQA.Selenium.StaleElementReferenceException: 'stale element reference: element is not attached to the page document

I tried a try catch block but that did not work. Thanks in advance.

timbre timbre
  • 12,648
  • 10
  • 46
  • 77

2 Answers2

1

You may try this by reassigning WeekDays value,

IList<IWebElement> WeekDays = Chromedriver.FindElements(By.XPath("//td[@class='dxeCalendarDay']"));

foreach (IWebElement Days in WeekDays)
{
    string WeekDaysResults = Days.Text;

    if(string.IsNullOrEmpty(WeekDaysResults))
    {
        //Do Nothing
    }
    else
    {
        if(WeekDaysResults == FirstDayOfCurrentMonth)
        {
            Days.Click();
            Debug.WriteLine("Week Days: " + WeekDaysResults);
        }        
    } 
    WeekDays = Chromedriver.FindElements(By.XPath("//td[@class='dxeCalendarDay']"));
}
Ishita Shah
  • 3,955
  • 2
  • 27
  • 51
0

A stale element reference exception is thrown in one of two cases, the first being more common than the second:

The element has been deleted entirely. The element is no longer attached to the DOM.

References: https://www.seleniumhq.org/exceptions/stale_element_reference.jsp