I am automating my current project. In that am trying to click on the main menu.

For that below is my code

WebElement ul = driver.findElementByXPath(prop.getProperty("category"));
    List<WebElement> options = ul.findElements(By.tagName("li"));
    for(WebElement sample: options)

When I run this code the main menu is getting clicked and it gets loaded but still am getting Stale Element reference error exception. Help me to resolve this.


Exception in thread "main" 
org.openqa.selenium.StaleElementReferenceException: stale element 
reference: element is not attached to the page document

HTML code:

enter image description here

2 Answers 2


Add a break at the end of if statement


Assuming the solution from the answer you have accepted as correct worked for you, I would suggest you to reconsider the logic of your code.

You do not need to iterate throughout the entire list for only looking up the element containing the text. It is better to look up that element using for example xPath locator.

This will let you to:

  • save time for test execution
  • avoid stale element exceptions
  • You are saying to give Xpath like this right? Ex: //a[contains(text(),'data')] Commented Jun 21, 2018 at 10:22
  • Exactly. you only should build a proper string using the value that your data variable contains.
    – Alexey R.
    Commented Jun 21, 2018 at 10:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.