Choose an option from a dropdown menu using JavaScript

Currently, I am working on a project that involves using javascrypt in conjunction with selenium. While attempting to search for and select an item from a list, I have encountered difficulties in selecting the element even after successfully locating it. If anyone can provide guidance or assistance on how to resolve this issue, I would greatly appreciate it. Thank you.

var input = document.evaluate("//li[contains(., 'ATACAMA')]", document, null, XPathResult.ANY_TYPE, null );

var thisregion = input.iterateNext();
thisregion.click();

https://i.stack.imgur.com/zICuo.png

Answer №1

Consider utilizing the code snippet provided:

var selection = document.evaluate("//li[text()='ATACAMA']", document, null, XPathResult.ANY_TYPE, null );

var chosenOption = selection.iterateNext();
chosenOption.click();

Answer №2

Although I'm not familiar with Xpath, as you mentioned, there's no restriction in using querySelector or querySelectorAll.

In this code snippet, an array of all li elements is created and the element containing the text "Item 3" is retrieved using .find. Subsequently, the element is programmatically clicked. Each li element has an inline onClick event defined in the HTML.

Do you think this approach would suit your needs?

let li_item = Array.from(document.querySelectorAll('li'))
              .find(x => x.textContent === 'Item 3');

li_item.click();

function select(element, n) {
  element.style.color = "red";
  console.log(`${n} has been selected!`);
}
<ul>
  <li onClick = "select(this, 1)">Item 1</li>
  <li onClick = "select(this, 2)">Item 2</li>
  <li onClick = "select(this, 3)">Item 3</li>
  <li onClick = "select(this, 4)">Item 4</li>
  <li onClick = "select(this, 5)">Item 5</li>
</ul>

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

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

What options do I have for personalizing this Google Bar Graph?

I am currently working on creating a Google bar chart. You can view my progress here: http://jsfiddle.net/nGvdB/ Although I have carefully reviewed the Google Bar Chart documentation available here, I am struggling to customize the chart to my needs. Spec ...

When using AngularJS, encountered an issue where a view was not updating with new data from a $http request

When making a request to the 500px API using $http for popular photos, the response object is successfully returned. However, I am facing difficulty in pushing the retrieved photo items to the view. Below is my current controller code: meanApp.controller ...

What are the possible complications that could arise from implementing this system for designing web pages?

Feeling frustrated with the limitations and compatibility issues of CSS, I decided to create a new approach for structuring webpages. Instead of relying on CSS, I developed a javascript library that reads layout instructions from XML files and uses absolut ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Is there a way to eliminate the need for using Xpath?

As a beginner to Protractor, I recently came across the style guide in the official documentation which strongly advises against using XPath locators. The reasons provided are solid: it's slow, easily prone to changes, and difficult to debug. But wha ...

Experimenting with kendoGrid information through cucumber capybara

I am currently working on creating cucumber and capybara tests to validate data within a KendoGrid UI component. I am facing challenges in figuring out how to select and verify the data displayed on the page. While there are basic tutorials available for ...

Stop HTML <dialog> from automatically closing using Vue

I'm working on a project where I need to use Vue to programmatically prevent an HTML dialog element from closing when the close event is triggered. Here's the code snippet I am currently using: import {ref} from 'vue'; const dialogTe ...

Having trouble with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allo ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...

Unrecognized files located within the same directory

My main.html file located in the templates folder also contains three additional files: date.js, daterangepicker.js, and daterangepicker.css. Despite including them in the head of the HTML as shown below: <script type="text/javascript" src="date.js"> ...

Initiate a POST request to download the file upon clicking the button

How can I initiate a file download when a button is clicked? During testing, I noticed that sending a GET request using <Link href="/api/generate-pdf"> works perfectly and the PDF file gets saved. However, when I use a button to hit the API, the dow ...

Jest throws an error: require function is not defined

I've been struggling with an issue in Angular for the past 3 days. I'm using [email protected] and [email protected]. I even tried downgrading and testing with LTS versions of node and npm, but I keep encountering the same error. Here ...

Attempting to utilize Selenium code in order to continuously refresh a webpage until a button becomes clickable

After receiving valuable assistance from the online community, I managed to create a script that can navigate through a webpage and join a waitlist. The issue arises when the 'join waitlist' button is not clickable because the waitlist is not ope ...

Guide on extracting an Array from JSON in a $.ajax response

I received a JSON value that was converted from an array in the AJAX response. {"Text":"Please provide a value","Email":"Please provide a value"} My goal is to extract the response JSON and display it within a div using $(div).html(): Text-Please provid ...

Preventing page refresh with Javascript when clicking on CAPTCHA

I have been exploring a CAPTCHA tutorial on TutsPlus.com and I am facing an issue where the 'Incorrect Captcha message' keeps appearing, indicating that my user input through $_POST does not match the stored $_SESSION string. Upon investigating ...

Acquire the website link using Selenium in the Python programming language

As a beginner in Python, I am excited to dive into web scraping and have chosen the following website as my target: Link After some research, I believe that Selenium is the best tool for the job. To get started, I wrote the code snippet below: from selen ...

Establishing a global variable in Cypress through a function

My current workflow involves the following steps: 1) Extracting a field value from one page: var myID; cy.get('#MYID'). then(($txt) => { myID= $txt.text(); }) .should('not.equal', null); 2) Mo ...

Error: Uncaught TypeError - Unable to access the 'handleClick' property of undefined within a forEach loop

I came across the following code snippet articles_list.jsx import React from 'react'; import './articles_list.css'; export default class ArticlesList extends React.Component { constructor(props) { super(props); this.state ...

Displaying a pair of values using a single noUISlider

I'm trying to achieve something unique with a noUIslider range by outputting two values. While I've managed to display the same value twice using examples from the noUIslider documentation, my goal is to have one of the outputs show a value that ...