user1853840
user1853840

Reputation: 21

Selenium WebDriver - StaleElementReferenceException when using click()

Sometimes when I execute code like this:

webDriver.findElement(By.xpath("//*[@class='classname']")).click();

I get this exception: org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM I know I could do a retry, but does anyone know why this happens and how I can prevent it?

Upvotes: 2

Views: 1323

Answers (2)

Maxim Kim
Maxim Kim

Reputation: 171

I had the same problem.

My solution is:

webDriver.clickOnStableElement(By.xpath("//*[@class='classname']"));
...
        public void clickOnStableElement(final By locator) {
            WebElement e = new WebDriverWait(driver, 10).until(new ExpectedCondition<WebElement>(){
                public WebElement apply(WebDriver d) {
                   try {
                       return d.findElement(locator);
                   } catch (StaleElementReferenceException ex) {
                       return null;
                   }
               }
            });
            e.click();
         }  

Hope it would help you. ;)

Upvotes: 2

Algiz
Algiz

Reputation: 1288

webDriver.findElement(By.xpath("//*[@class='classname']"))

returns you a WebElement object.

A WebElement object refer always to a node into the HTML DOM tree (within the memory of your web browser).

You got this exception when the node in the DOM tree does not exist anymore. The WebElement object still exist because it is inside the JVM's memory. It is kind of "broken link". You can call method on the WebElement but they will fail.

Upvotes: 0

Related Questions