2

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?

2
  • Seems that this element was deleted from Document. Maybe some javascript deleted it. Maybe your code executes too fast and that element doesn't appears after some javascript logic? Commented Feb 6, 2014 at 15:03
  • Take a look at this - Stale Element Reference Exception Commented Feb 6, 2014 at 15:05

2 Answers 2

2

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. ;)

Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.