Using Javascript with Selenium to choose an item from a dropdown menu

I'm having trouble selecting an element from a dropdown list and interacting with it.

The xpath for the element I'm trying to select from the dropdown is:

/html/body/div[1]/div/div[1]/div[1]/div[2]/div/div/div[1]/div[2]/div[1]/div/div/div/div[2]/div/div/ul/li[2]

The dropdown window has the id rw_2_input

The dropdown list offers five options: less than 18, 18-40, 40-60, and so on. Here's what I've tried:

// Select the dropdown and click on it
const age = await driver.findElement(By.id('rw_2_input'))
await age.click()

Then,

// Select the dropdown item and click on it

    const ageChoice = driver.wait(until(elementIsVisible((By.XPATH, "/html/body/div[1]/div/div[1]/div[1]/div[2]/div/div/div[1]/div[2]/div[1]/div/div/div/div[2]/div/div/ul/li[2]"))))
    await ageChoice.click()

At the top of the file, I have imported these modules:

const { Builder, By, Key, util } = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome')
const expect = require('expect')
const { elementIsVisible } = require('selenium-webdriver/lib/until')

The issue I'm facing is that it says until is not defined.

I believe there's an error in my importing process, but I am unsure of where the mistake lies. I referred to this documentation to understand the correct way to import, but I couldn't find a solution. If I try to select the element in the dropdown using

const ageChoice = await driver.findElement(By.xpath('/html/body/div[1]/div/div[1]/div[1]/div[2]/div/div/div[1]/div[2]/div[1]/div/div/div/div[2]/div/div/ul/li[2]'))
await ageChoice.click()

It returns an error stating:

ElementNotInteractableError: element not interactable

Why is it not interactable? I am confused.

* * *

***** UPDATE: *****

I managed to make some progress, but I still encounter the "Element not interactable" error: What I did was

const ageChoice = await driver.findElement(By.xpath("//li[contains(text(),'Tra 19 e 40')]"))
await ageChoice.click()

If I comment out the .click() function everything works fine, but the option is not selected. How can I select it despite being told that it is not interactable?

Answer №1

Here's a possible workaround that might help in the short term. (It's not a permanent solution). You have the ability to run JavaScript directly on the web page by using this command driver.executeScript(command).

To target a specific element by its ID and trigger JavaScript, you can use the following as an example:

driver.executeScript('document.getElementById('#someID').click()')

Answer №2

After much trial and error, I have finally identified the root cause of the issue and am documenting it here for future reference.

It turns out that the presence of 2 dropdown lists on my webpage was causing a problem. When I selected an option from the first dropdown, the options momentarily overlapped with the second dropdown, leading to a "not interactable error".

Upon discovering this issue (which unfortunately took hours as it is not mentioned in any documentation), I found a way to effectively "wait" for the first dropdown to close.

The solution involves performing two specific checks:

a) Ensure that the element is visible.

b) Confirm that it is enabled.

Without these checks, the code will not perform as expected. Here is the revised code snippet:

const ageChoice = await driver.findElement(By.xpath("//li[contains(text(),'Tra 19 e 40')]"))
await driver.wait(until.elementIsVisible(ageChoice), 3000)
await driver.wait(until.elementIsEnabled(ageChoice), 3000)
await ageChoice.click()

By incorporating the elementIsVisible and elementIsEnabled functions within the wait-until method, there is no need for elementLocated. This alternative code snippet should be avoided:

const ageChoice = await driver.wait(until.elementLocated(By.xpath(By.xpath("//li[contains(text(),'Tra 19 e 40')]"))

If you encounter a situation where these two checks are unnecessary but the element is located at the bottom of a page with multiple dropdowns, resulting in timing out before being accessed, then use the following approach:

const ageChoice = await driver.wait(until.elementLocated(By.xpath(By.xpath("//li[contains(text(),'Tra 19 e 40')]"))
ageChoice.click()

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

Implementing clickable actions to add new entries in a React.js application (using Redux toolkit)

I am currently working on my PET project using Redux toolkit and encountering some issues with inputs. When I add an input on click, it gets added correctly, but I am unsure if it is being added in the right place (it should be added in the ITEMS array). A ...

Struggling to animate the selector of a nested div in Jquery?

Despite trying numerous variations, I am struggling to identify the correct selector of a nested div. The goal is to animate this particular div, but since no animations are taking place, I suspect that I have not selected the right element. Here is the a ...

Create a dynamic table using an array in jQuery

Currently, my goal is to generate a table using an array with the following format: [ { header: 'ID', values: [1, 2] }, { header: 'First Name', values: ['John', 'Jayne'] }, { header: &ap ...

The functionality of Vue is acting up with the HTML, unexpectedly refreshing when a button is clicked

I am currently experiencing an issue with my Vue application. When I click the button, it clears the input field (which it shouldn't) and doesn't perform any other actions. The variables "codigo" and "payload" do not display anything on the scree ...

Can you provide guidance on integrating this jQuery script into my Next.Js application effectively?

I have been using a script on a plain HTML website, importing it via the <script> tag: (function($) { var wa_time_out, wa_time_in; $(document).ready(function() { $(".wa__btn_popup").on("click", function() { if ($(&qu ...

Unpredictable Redirection when URL is Clicked using PHP or Javascript

Looking to send users to a random URL from a specific list? For instance: With 3 URLs available - Google.com, Facebook.com, and Yahoo.com <a href="<?php $sites[array_rand($sites)] ?>">Click here</a> Upon clicking the link, users will ...

What could be causing the absence of the ID definition?

Whenever I send a DELETE request, I receive an error message stating ReferenceError: id is not defined at Object.removeOne (...\services\user.js:16:38. I am unsure about the role of 'id' in \services\user.js and why it is not ...

Does the html label prevent propagation from occurring?

Can anyone explain why the toggle function is not being executed when clicking inside the box with the black border, but works when clicking outside of it (although not on the checkbox)? var checks = document.querySelectorAll("ul li"); for (var i = 0 ...

Tips for setting up Highcharts tooltip.headerFormat using the function getDate() plus 5

I'm facing a little challenge trying to understand how the JavaScript function getDate interacts with Highcharts datetime on xAxis. My goal is to show two dates in the tooltip header, forming a date range like this: 1960/1/1 - 1965/1/1. The first da ...

Coordinating Angular to communicate with Node.js to send and receive data

I am currently working on a project using express.js, but I would like to integrate angular into the project to create a single page application. The website currently refreshes the entire content from the server whenever a link is clicked, which seems ine ...

Use Node.js to transform every spreadsheet into Json format

I have been attempting to convert an Excel file into JSON format. I tried utilizing the "xls-to-json" npm package with the following code: node_xj = require("xls-to-json"); node_xj({ input: "Auto.xlsx", // input xls output: "output.json", // output ...

Minimize the number of HTTP requests by including CSS and JS files in PHP

I've been considering a method to reduce the number of HTTP requests made when loading a page by minimizing the amount of downloaded files, while still keeping separate files on the server. The thought process is as follows: <!DOCTYPE html> &l ...

Navigating through the Robot Framework: Extracting specific data from a cell in an xlsx document

As someone who is new to Python and the Robot framework, I am looking to extract specific cell data for automation purposes. I have tried using the `Library ExcelLibrary` and a command Read Cell Data By Coordinates {Path to my excel file}/test.xlsx ...

"Converting domain names with punycode and utilizing Firebase for a

My current project involves updating a Firebase app with NextJS, and I've encountered an issue that needs to be resolved. Upon running the command: % npm run build I received the following message: (node:3719) [DEP0040] DeprecationWarning: The `pun ...

Tips on implementing Dynamic arrays in the useEffect hook within React applications

Does anyone have experience with using a dynamic array as input in the dependency array of the useEffect hook? I'm encountering an issue where the array is being passed as a string and therefore not triggering the hook correctly. const [formData,setFo ...

Exploring the process of acquiring a button using refs in external JavaScript

Having encountered a situation where I have two different javascript files, I came across an issue. The first file contains a finish button that was initialized by using refs. Now, I need to access this button in the second file using refs. The code snipp ...

Monitor the user's attendance by utilizing two separate for loops

I'm currently developing an angularjs attendance tracking system and I'm facing challenges when it comes to accurately counting the number of days an employee is absent. Despite attempting to solve this issue with two nested for loops, I am still ...

What causes setInterval to create an endless loop when used inside a while loop in JavaScript?

I attempted to initiate a delayed "one" call or a "one or two?" question, but instead of working as expected, the function continued running indefinitely. Surprisingly, everything worked perfectly fine without using setInterval. quester2() function quest ...

"Utilizing the power of mapping in React to dynamically generate and return an

Hello everyone! I'm currently working on a project where I am making a get request to a Google API and fetching some data. Initially, the state value is empty, but after receiving the ajax response, I expect the state values to be updated using setSta ...

Enhancing JavaScript form validation techniques

I am currently working on a user profile form that includes 15 text fields, dropdown menus, and a textarea. Users can input information into these fields, and upon saving the form, not all fields are required to be filled out. However, I need to validate a ...