RJ not Radio Jackey
RJ not Radio Jackey

Reputation: 61

Protractor: Failed: stale element reference: element is not attached to the page document after click()

I am facing above issue when i am trying to click on the dropdown element which matches with given text. All the options of dropdown are as in the image with span having the text. I tried things given as in the link here,but no success. Protractor: Failed: stale element reference: element is not attached to the page document. Reference of tags are as given here in this pic below. The tags used are <ul><li>.

My code looks something like this

element.all(by.css('ul[class='ui-dropdown-items ui']>li')).each(function(element) {
  element.getText().then(function (text) {
     if (text.includes("Bag")){
       element.click();
     }
  });
});

Though the click action gets performed by above statement, still error is thrown. Also when i try to click on any index as hard coded it works with no error. element.all().get(4), where 4 being index of the element. My application is in angular 5. Can someone help me out on this! This is blocking my project.

Upvotes: 0

Views: 509

Answers (1)

yong
yong

Reputation: 13712

element.all().each() execute iteration on each element, even you add if condition to only click one element of all, But the getText() in each iteration still be executed.

After you click on the matched element, the page redirected or refreshed. Then call getText() on next element on "new" page, that's why report stale reference exception

You need to filter the matched element, then click on it.

// approach 1
element
.all(by.css('ul[class='ui-dropdown-items ui']>li'))
.filter(function(ele) {
  return ele.getText().then(function (text) {
     return text.includes("Bag");
  });
})
.then(function(eles){
    if (eles && eles.length > 0) {
        eles[0].click()
    } 
})

// approach 2
let options = element.all(by.css('ul[class='ui-dropdown-items ui']>li'))

options.getText(function(txts) {
  return txts.findIndex(function(txt){
    return txt.includes('Bag');
  })
})
.then(function(index){
    return index !== -1 && options.get(index).click();
})

Upvotes: 3

Related Questions