Compound classes stored in an array are not accessible in selenium java

51 views Asked by At

What my issue is after clicking on a button it shows some 6 options and i need to store the compound class name of those options since i need to click on each of those options .But when i am trying to store class name in array and start iterating it successfully clicks on 1st option but when try to click on second option it gives exception "org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM". Where i am doing mistake.

this is the code to iterate over classes stored in array :

List<WebElement> elementsList = new ArrayList<WebElement>(); 
elementsList = ArrayList<WebElement>)driver.findElements((By.cssSelector(".simpleButtonWidget")‌​)); 
Iterator itr = elementsList.listIterator(); 
while(itr.hasNext()) { 
    WebElement tempElement = (WebElement)itr.next(); 
    tempElement =(WebElement)itr.next(); 
    tempElement.click(); 
}

Page code:

<div class="toolsMenuWidget"> 
<div id="toolsMenuJPlayer" class="jp-jplayer" style="width: 0px; height: 0px;"></div> 
<div class="simpleButtonWidget ConnectingCubesBtn choice_1 up" style="cursor: pointer;" title="Connecting Cubes"></div> 
<div class="simpleButtonWidget NumberCardsBtn choice_2 up" style="cursor: pointer;" title="Number Cards"></div> 
<div class="simpleButtonWidget PlayMoneyBtn up choice_3" style="cursor: pointer;" title="Play Money"></div> 
<div class="simpleButtonWidget PosterBtn up choice_4" style="cursor: pointer;" title="100 Poster"></div> 
</div> 
1

There are 1 answers

0
Würgspaß On

The second line of your while loop is certainly wrong:

while(itr.hasNext()) { 
    WebElement tempElement = (WebElement)itr.next(); 
    tempElement =(WebElement)itr.next(); //remove this
    tempElement.click(); 
}

But as Vikas Neha Ojha points out, a StaleElelmentReferenceException may be thrown, if the DOM changes after you have clicked on the first element. In that case you need to look up every element again. Given that the titles of the elements are stable this should work:

String[] titles = { "Connecting Cubes", "Number Cards", "Play Money", "100 Poster" };
for (String title : titles) {
    WebElement element = driver.findElement(By.xpath("//div[@title='" + title + "']"));
    element.click();
}