Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in DevOps and Agile by (19.7k points)

I get this error when running my tests: org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM

Any idea on how to solve the above exception? This happens in Selenium Grid which has a ref Xpath expression which is dynamic

1 Answer

0 votes
by (62.9k points)

Solution 1:

You could refresh the page and check out once more for the same element.

Assume you're attempting to click on a link and obtaining the stale element exception.

Sample code to overcome the issue

driver.navigate().refersh();

driver.findElement(By.xpath("xpath here")).click();

Solution 2:

If an element is not attached to DOM then you could try using ‘try-catch block’ within ‘for loop’

// using for loop, it tries for three times.

// If the element is found for the first time then it breaks from the for loop and comes out of the loop

for(int i=0; i<=2;i++){

  try{

     driver.findElement(By.xpath("xpath here")).click();

     break;

  }

  catch(Exception e){

     System.out(e.getMessage());

  }

}

Solution 3:

Wait for the element till it gets available

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("table")));

Use ExpectedConditions.refreshed to avoid StaleElementReferenceException and retrieve the element again. This method updates the element by redrawing it and we can access the referenced element.

.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf("table")));

I hope this helps!

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, enroll in industry based Selenium online courses.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...