Protractor fails to proceed to the next line following a click from the dropdown menu

Utilizing protractor to interact with dropdown menus can be tricky, especially when the elements have dynamically changing IDs. To tackle this issue, I have been using element.all to retrieve text values and implementing if conditions to compare them against my desired selection in order to click on the correct item.

<div class="ng-trigger ng-trigger-transformPanel ng-tns-c4-15 mat-select-panel mat-primary ng-star-inserted" style="transform-origin: 50% 127.5px 0px; font-size: 14px; opacity: 1; min-width: calc(100% + 32px); transform: scaleY(1);">
            <!---->
            <mat-option _ngcontent-c20="" class="mat-option ng-star-inserted" role="option" tabindex="0" id="mat-option-59" aria-selected="false" aria-disabled="false">
                <!---->
                <span class="mat-option-text"> Cik </span>
                <div class="mat-option-ripple mat-ripple" mat-ripple=""></div>
            </mat-option>
            <mat-option _ngcontent-c20="" class="mat-option ng-star-inserted" role="option" tabindex="0" id="mat-option-60" aria-selected="false" aria-disabled="false">
                <!---->
                <span class="mat-option-text"> Dato' </span>
                <div class="mat-option-ripple mat-ripple" mat-ripple=""></div>
            </mat-option>
            <mat-option _ngcontent-c20="" class="mat-option ng-star-inserted" role="option" tabindex="0" id="mat-option-61" aria-selected="false" aria-disabled="false">
                <!---->
                <span class="mat-option-text"> Dato Paduka </span>
                <div class="mat-option-ripple mat-ripple" mat-ripple=""></div>
            </mat-option>

The approach I've taken is as follows:

function Select(title){
    element(by.name("title")).click().then(function(){
        browser.sleep(1000)
    })
    element.all(by.tagName("mat-option")).each(function(item){
        item.getAttribute("id").getText().then(function(z){
            if(z==title){
                item.click().then(function(){
                    console.log("Successfully selected title");
                    })
                }       
            })
        });

However, a major hurdle I've encountered is that after clicking on an option, Protractor returns to the top and attempts to search for elements again. This leads to failures as the dropdown menu is already closed at this point. It fails to proceed to select other fields.

Below is the error message I receive post successful selection:

Failed: The element reference of <mat-option id="mat-option-575" class="mat-option ng-star-inserted"> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed

Any suggestions on how to overcome this issue without encountering errors?

Answer №1

It seems like your approach involves using a loop solely for the purpose of selecting and clicking on the correct option. However, looping in this manner may not be necessary and could potentially lead to overlooking any exceptions if the expected title is not found.

If my understanding is accurate, you might consider directly locating the element and performing the click operation. But if there are other constraints that I have overlooked, please feel free to inform me.

function SelectOption(title) {

    element(by.name("title")).click().then(function () {
        browser.sleep(1000);
        element(by.xpath(`//mat-option[text()='${title}']`)).click()
            .then(function () {
                console.log(`Clicked on the option containing ${title}`);
            })
        //alternative locator to try
        // element(by.xpath(`//mat-option/span[text()='${title}']/parent::mat-option`))
    })
};

Answer №2

I found this solution to be effective in addressing my specific situation. Special thanks to @DublinDev for the helpful advice :)

function ChooseTitle(title) {

    element(by.name("title")).click().then(function () {
        browser.sleep(1000);
        element(by.cssContainingText('mat-option',title)).click().then(function () {
                console.log("Title clicked successfully");
            })
    })
};

Answer №3

Here is a useful function for you to try out.

async function ChooseOption(option){
    await browser.sleep(1000);
    await element(by.name("title")).click();
    await browser.sleep(1000);
    const elements = element.all(by.css('div>mat-option>span.mat-option-text'));
    for(i=0;i< elements.count();i++){
       if(await elements.get(i).getText() === option){
            await browser.sleep(1000);
             await elements.get(i).click();
             await browser.sleep(1000);
             break;
        }
     }
  }

I hope this function proves helpful for your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching the image when a key is released: A step-by-step

I'm currently developing a small game utilizing HTML5 canvas and javascript. My goal is to create an image that moves from left to right, with the ability to change its appearance when a key is pressed. While I have successfully implemented movement ...

Create arrays to display their respective index numbers

Here is an array that I am working with: var myArray = [12, 24, 36, 48, 60, 15, 30]; I am trying to create a new array of arrays that includes the index numbers from the original array in the new array. The final result should be formatted like this: va ...

What could be the reason behind the appearance of borders in my modal window?

I can't seem to find the source of the 2 silver borders in my modal. I've checked the CSS code, tried using developer tools, and looked through the entire code but still can't figure it out. Here is the JSX code I'm working with: impor ...

Pop-up that appears based on the location of the mouse click

I am looking for a rollover popup that is triggered by the location of a mouse click. I am unable to use a CSS absolute positioned div inside a relative one because it causes my popup to be cropped due to overflow:hidden being set for layout purposes. The ...

Removing particular elements from a numpy array: A step-by-step guide

Is there a way to eliminate certain elements from a numpy array? For example, if I have import numpy as np a = np.array([1,2,3,4,5,6,7,8,9]) I am looking to remove 3,4,7 from a. The only information I have is the index of these values (index=[2,3,6]). ...

What is the best way to retrieve JSON data from a variable once it has finished loading?

let jsonDataNewsFeedGlobal; jsonDataNewsFeedGlobal = $.getJSON('').done(function(data) { console.log(data); console.log(data.source); }); My Challenge: I see my mistake now, I should have been using "data" instead of "jsonDataNewsFeedGlobal ...

The Next.js API endpoint is struggling to process cross-domain POST requests

Dealing with a POST request in my NextJS application has been challenging. This particular post request is originating from a different domain. To address this issue, I included a receptor.ts file in the /pages/api directory: import { NextApiRequest, Next ...

Creating an HTML Canvas using an AngularJS template

I am facing an issue with rendering html elements on a canvas using html2canvas JS. I am utilizing AngularJS for data binding on the html page, but unfortunately, the dynamic data is not showing up on the canvas generated from these html elements. For inst ...

What is preventing me from deleting cookies on Express?

Whenever a new user is registered, the number of cookies just keeps increasing endlessly. userRoutes.js: const { registerUser, loginUser, registerVerify } = require("./userController"); const express=require('express') const router=ex ...

ExpressJS Template Caching System

Encountering issues with template caching in my MEAN app. The navigation bar uses conditional logic to show/hide buttons based on user status. Upon page load, values are null or false until login (views, isLoggedIn). The problem arises post-login - despit ...

transfer the reference of "this" to a function within the on() method

I'm currently working with the code snippet below. What it does is, when a user hovers over a link, it logs this to the console. var Mod = function () { $('.link').hover(this.hover, this.out); }; Mod.prototype = function () { var h ...

Button in C# .NET integrated with Bootstrap Modal fails to trigger on the server-side

In my .net C# project, I am utilizing a repeater to showcase data. Each item in the repeater has an "EDIT" button that is expected to open up a modal displaying relevant information. I want this button to not only trigger the modal but also retrieve the ne ...

The application is unable to locate the installed packages

I have successfully installed formik and yup by running npm install formik and npm install yup. Both packages are listed in the dependencies object of package.json. In my file, I import them as follows: import * as Yup from 'yup'; import { For ...

Facing a few hiccups in JavaScript or CSS code, but getting closer to making it work

Here is the code I currently have with HTML, CSS, and JavaScript. Everything is working correctly except for one small issue that I can't seem to resolve. I am new to JavaScript and believe that JavaScript is necessary to fix this problem. If not, the ...

Tips for efficiently importing a file or folder that is valuable but not currently in use

I'm struggling to find any information about this particular case online. Perhaps someone here might have some insight. I keep getting a warning message saying 'FournisseursDb' is defined but never used no-unused-vars when I try to import t ...

Create an index.html file using webpack to utilize it with the development server

Using webpack to run my Three.js application, I have the following configuration in the webpack.config file: module.exports = { entry: `${__dirname}/src/tut15.js`, output: { path: __dirname + '/dist', filename: 'index_bundle.js&a ...

Tips for styling the chosen option in a dropdown menu with <ul> and <li> tags

I am having trouble logging the selected dropdown value to the console in this code snippet. HTML <div class="dropdown"><button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" ...

Is there any HTML code that is able to implement a currency format identical to the one we've customized in Google Sheets/Google Apps Script

I am currently working with a Google Sheet table that consists of 2 columns. The second column contains charges which can vary based on user input through a Google Form and are summed up using GAS. To view an example, click here. The data from this Googl ...

find the next earliest date in the array after the specified date

How can I find the smallest date in an array of dates that comes after a specific date? var datesArray = ['2019, 10, 4', '2019, 10, 13', '2019, 10, 8', '2019, 10, 6']; ownDate = '2019, 10, 05'; I need to ...

Tips on adding new information into React.js

I'm encountering an issue with React JS where I need to display all the data in a row instead of a column. What changes should I make in my code to achieve this? Here's a link to a working demo: https://codesandbox.io/s/nostalgic-wood-9jrib?fi ...