Locate element based on its specific property value

Currently, I am conducting tests on a web application utilizing Nightwatch.js, which relies on Selenium WebDriver for browser interactions. Within my application, there is a list of items that are dynamically created and only differentiated by their names, displayed as input values. The task at hand is to locate an item based on its name.

Below is an example of the HTML representation of the document structure:

<div class="item">
  <input>  <!-- current value: "first" -->
</div>
<div class="item">
  <input>  <!-- current value: "second" -->
</div>
<div class="item">
  <input>  <!-- current value: "first" -->
</div>

The goal is to identify the div.item that contains an input with the value second.

It is important to note that the value of an <input> is determined by the value of its value property, which may differ from the value of its value attribute. Due to DOM manipulation by React in my case, the inputs may not possess the value attribute at all.

Is there a method to locate an element based on its property value using Nightwatch (or Selenium WebDriver API)?

After reviewing the WebDriver documentation and exploring alternatives such as executing custom JavaScript code, I have encountered certain limitations (e.g., the need for a custom implementation of waiting for an element to appear and a lack of interaction with Nightwatch page objects). From my perspective, the other methods primarily focus on examining the HTML structure only (thus, dealing with attributes at best, not properties).


Just to clarify, the utilization of selectors like input[value=...] (CSS) or //input[@value=...] (XPath) is not a viable solution, as they search for attribute values rather than property values.

Answer №1

To retrieve a list of elements with the class "item" using the .elements() method, and then loop through each element by utilizing .getValue() to access the value property of each input. If the value matches the desired name, the element is returned.

function findElementsByValue(xpathSelector, expectedValue, callback) {
  const matchedElements = [];
  browser.elements('xpath', xpathSelector, ({ value }) => value.forEach(inputEl => {
    browser.elementIdValue(inputEl.ELEMENT, result => {
      if (result.value === expectedValue) {
        matchedElements.push(inputEl);
      }
    });
  });
  browser.perform(() => callback(matchedElements));
}

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

Encountered an Unexpected Token SyntaxError in Node.js

When setting up the routers for the API, I have defined them for both POST and GET requests like this: var bookRouter = express.Router(); bookRouter.route('/Books') .post(function(req, res) { var bok = new book(req.body); con ...

Issue with WebDriver's FirefoxProfile User-Agent not functioning correctly

I have configured a user agent using WebDriver along with a FireFox Driver. Different iPhone and Android mobile devices have been set up with unique user agents that are intended to redirect to a mobile-optimized website. Here is the code snippet: Firefo ...

Tips for adjusting the order in which styles load in NuxtJS

I need to adjust the loading order of styles in my current project. In my custom stylesheet style.css, I've made some overrides, body { font-family: "Lato", sans-serif; font-size: 14px; font-weight: 400; font-style: normal; ...

Tips on sending asynchronous requests to a PHP page using jQuery AJAX

As a newcomer to web development, I am working on creating a social networking website for a college project. One feature I want to implement is updating the message count in the menu every time there is a new message in the database for the user (similar ...

Is it possible for the connectedCallback() method within a Custom Component to have varying interpretations based on the specific context in which it is implemented?

I have recently developed a Custom Component that incorporates a Vue instance: class ContentCardExample extends HTMLElement { connectedCallback() { const card = document.createElement('div'); card.setAttribute("id", "app") card.i ...

The Chrome Webdriver Refresh feature has been unresponsive ever since the release of Chrome version

Ever since I upgraded to Chrome 106 (and now 107), the driver successfully opens the URL on the first try. However, after a certain amount of time or under specific conditions, the driver.refresh() function does not provide a response. It seems that if the ...

Installing libraries using npm can be done in two ways: using the command `npm install`

While working, we encountered an issue where the icon for the menu block from the rc-menu library was not displaying. Every time we run mvn install We also run npm install In our package.json file, we had included this library "rc-menu":"^5.1 ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Ways to implement a suggestion feature similar to Java in Eclipse using Ruby

Is it possible in Ruby Eclipse to have a similar feature as in Eclipse Java where all available methods and variables are displayed when typing "." for external library methods? ...

The functionality of the MVC jQuery grid is currently malfunctioning

Recently, I attempted to integrate a jQuery grid plugin from gijgo.com into my MVC application. Following the instructions provided on c-sharpcorner and/or codeproject meticulously, however, upon running the application, I encountered a troubling JavaScrip ...

JavaScript function for validating CGPA or GPA fields

I am encountering issues with JavaScript validation in ASP.NET. The validation seems simple, but for some reason, it is not functioning properly. Below is the code that I have tried: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.as ...

Steps to initiating Firefox browser using GeckoDriver and Selenium

Having trouble launching the Selenium web browser. I can open Firefox but having issues with Google. Can someone help me with this error? package selenium1; import org.openqa.selenium.WebDriver; //import org.openqa.selenium.chrome.ChromeDriver; import or ...

Building a hierarchical object structure from an array

I am working with an array of objects that looks like this: const sorted = [ { IsoCode: "EUR", Buy: 1.948, Sell: 1.963 }, { IsoCode: "GBP", Buy: 2.1184, Sell: 2.1894 }, { IsoCode: "USD", Buy: 1.5781, Sell: 1.6484 }, ] and my ...

Ensure to check the input file for null values before proceeding

My task involves working with an input file: Razor: @Html.TextBox("archivo", "", new { type = "file",id = "archivo" } Html: <input id="archivo" name="archivo" type="file" value=""> I am trying to detect if the value of the input is null when a b ...

Ways to utilize/extract data from an enumeration

Hello there! I am currently diving into the world of React and Typescript, eager to expand my knowledge. Please bear with me if my explanations are not up to par. In my react app, I have a scenario where I created an enum that I want to utilize in two diff ...

Confirming Deletion with a Jquery and Ajax Popup Box

I am seeking assistance with a specific task. Although my function is functioning well with ajax, I am in need of an "ok" or "cancel" delete confirmation box before submitting the ajax request to remove an item from the database. Here is the code I am cu ...

Issue with Angular 2: scrolling event not triggering

Just starting out with Angular 2 and I'm trying to implement infinite scrolling for fetching data using REST API calls. Initially, I make a call like this to get the first set of 50 records: localhost:8080/myapp/records=items&offset=0&limit=5 ...

I successfully executed my first node.js http request, but it is now encountering an error

Utilizing the 'request' module in node.js for sending http requests has been successful initially. However, it is now returning an error. var request = require('request'); request('http://www.google.com', function (error, res ...

Maximizing the Benefits of Scrapy's Concurrency Using Non-Selenium Requests

Currently facing an intriguing challenge while developing a Scrapy web scraper for extracting products from a website. The obstacle lies in the fact that the catalog pages on the site utilize lazy-loading, restricting me to gather only the initial 12 items ...