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 Answers 2

2

Add a break at the end of if statement

if(sample.getText().equals(data)){
            sample.click();
            break;
        }
0
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
2
  • You are saying to give Xpath like this right? Ex: //a[contains(text(),'data')] Jun 21, 2018 at 10:22
  • Exactly. you only should build a proper string using the value that your data variable contains.
    – Alexey R.
    Jun 21, 2018 at 10:32

Your Answer

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

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