2

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)
    {
        if(sample.getText().equals(data)){
            sample.click();
        }
    }

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.

Error:

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

Add a break at the end of if statement

if(sample.getText().equals(data)){
            sample.click();
            break;
        }
| improve this answer | |
4

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
| improve this answer | |
  • You are saying to give Xpath like this right? Ex: //a[contains(text(),'data')] – Prasanna venkatesh Jun 21 '18 at 10:22
  • Exactly. you only should build a proper string using the value that your data variable contains. – Alexey R. Jun 21 '18 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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