codemon
codemon

Reputation: 1594

WebdDriverJS/ NodeJS: 'Element is not attached to the page document' Error

I am completely new to WebDriver (chromedriver) and only have super basic knowledge of javascript syntax so I'm sorry if my code looks like spaghetti.

I have a clickAllElements(); function that finds all elements in a class and clicks on them.

//Click every element of an array
var clickAllElements = function (el, screenShot){
    //Store elements in an array
    var findElements = driver.findElements(By.css(el));
    findElements.then(function (options) {
        //Then iterate through array
        options.map(function (elem) {
            //Click on each item in the array
            return elem.click().then(function() {
                //Then get the text content inside each element
                driver.sleep(5000);
                elem.getText().then(function(text){
                    //Log the text to the console.
                    console.log(" - Selecting " + text.trim());
                     driver.sleep(2000);
                    if (screenShot) {
                        takeScreenShot(text);
                    }                    
                });              
            });
        });
    });
}

This has worked fine but now I have the following three elements.

enter image description here

And here is the html/css for them as shown in Chrome inspector

enter image description here

I want my clickAllElements(); function to click on the x on each value so as to delete them. When I do clickAllElements('.token > a'); it actually does delete the first one, but after that I get a "stale element reference: element is not attached to the page document." I don't understand the error because those elements are clearly there. How can I get around this? (using a javascripit solution preferably);

Upvotes: 0

Views: 1617

Answers (1)

BVengerov
BVengerov

Reputation: 3007

There are two possibilities:

The element is deleted immediately after clicking, but is referenced later

elem.getText().then(function(text)

In this case you only need to NOT make further references to the object in case of delete links. Add a parameter to this function or, better yet, create another one just for deleting all links.

The element gets updated after clicking

You can also solve this by writing another function, but in this case you can also re-write the function to loop through each element by index, refreshing the list of elements each time after the click and getting the text from the one specified by index.

Upvotes: 2

Related Questions