3

I wanted to select option one by one from the drop down. But only first option is getting selected. my code is not able to select another option.

In below example, "Product Name: A to Z" is getting selected, but "Product Name: Z to A" is not getting selected. Please let me know if anybody aware of this issue.

This is HTML Source code:

<select id="selectProductSort" class="selectProductSort form-control">
     <option value="position:asc">--</option>
     <option value="price:asc" selected="selected">Price: Lowest first</option>
     <option value="price:desc">Price: Highest first</option>
     <option value="name:asc">Product Name: A to Z</option>
     <option value="name:desc">Product Name: Z to A</option>
     <option value="quantity:desc">In stock</option>
     <option value="reference:asc">Reference: Lowest first</option>
     <option value="reference:desc">Reference: Highest first</option>
</select>

This is my code trying to select two options one after another:

WebElement fieldSortBy = driver.findElement(By.id("selectProductSort"));
Select selectSortBy = new Select(fieldSortBy);
fieldSortBy.click();
selectSortBy.selectByVisibleText("Product Name: A to Z");
Thread.sleep(3000);
fieldSortBy.click();
selectSortBy.selectByVisibleText("Product Name: Z to A");

I am getting below exception:

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

  • Is there a lot of javascript magic going on on this element? If no, why are you waiting for 3 seconds and clicking the element? – FDM Apr 7 '18 at 19:07
5

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

Okay, this one seems to be explainable given the code you have. You see, what is happening here is that right after the selectSortBy.selectByVisibleText("Product Name: A to Z") line is executed your fieldSortBy dropdown element reference becomes "stale" because its DOM representation changed (documentation reference). This is a common problem when working with selenium.

The usual way to solve this kind of problems is to "refresh" the element reference - "re-find" the element:

WebElement fieldSortBy = driver.findElement(By.id("selectProductSort"));
Select selectSortBy = new Select(fieldSortBy);
fieldSortBy.click();
selectSortBy.selectByVisibleText("Product Name: A to Z");
Thread.sleep(3000);

# FIX HERE v
WebElement fieldSortBy = driver.findElement(By.id("selectProductSort"));
# FIX HERE ^
fieldSortBy.click();
selectSortBy.selectByVisibleText("Product Name: Z to A");

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.