0

I got an error message. This error general can be but I can't solve it in my code. Is can anyone help me?

Explanation:

I am taking airline code from in a loop, but when if(){} condition start to process. I receive an error

Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM

This is just one of the all li tags. The total number of li tag is 9.

<li data-airline-id="SU">
    <input id="airline_SU" type="checkbox" checked="checked" title="Aeroflot">
    <label for="airline_SU" class="clearfix">

            <span class="day-filters-label-price">$939</span>

        <span class="day-filters-label-message">Aeroflot</span>
    </label>
</li>

Java Code:

ul = driver.findElements( By.xpath( "//div[@id='filters-airlines']//ul[@class='clearfix']/li" ) );

    for( WebElement element : ul ){

        String countryCode = element.getAttribute( "data-airline-id" );

        System.out.println( countryCode );

        if( !"DE".equals( countryCode ) ){

            element.findElement( By.id( "airline_" + countryCode ) ).click();

        }

        try{
            Thread.sleep( 1000 );
        }
        catch( InterruptedException e ){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
soduncu
  • 51
  • 1
  • 9
  • Take a look at the examples provided here http://stackoverflow.com/questions/5709204/random-element-is-no-longer-attached-to-the-dom-staleelementreferenceexception – rkkrazyivan Aug 12 '14 at 09:28

1 Answers1

1

You may use a 'hack'. To avoid StaleElementReferenceException you have to relocate an element before some action with it. If I understand your logic, you want to uncheck all checkboxes but the 'DE'. You locate li's with the XPATH //div[@id='filters-airlines']//ul[@class='clearfix']/li. So you can relocate it every time with given index

ul = driver.findElements( By.xpath( "//div[@id='filters-airlines']//ul[@class='clearfix']/li" ) );

for( int i = 1; i <= ul.size(); i++ ){

    WebElement li =  driver.findElement( By.xpath( "(//div[@id='filters-airlines']//ul[@class='clearfix']/li)[" + i + "]" ) );

    String countryCode = li.getAttribute( "data-airline-id" );

    System.out.println( countryCode );

    if( !"DE".equals( countryCode ) ){

        li.findElement( By.id( "airline_" + countryCode ) ).click();

    }

    try{
        Thread.sleep( 1000 );
    }
    catch( InterruptedException e ){
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

PS I don't use Java so syntax may be broken a little

Furious Duck
  • 2,009
  • 1
  • 16
  • 18