The action of clicking on the div element designated with the role of 'button' is not functioning as expected

The issue arises when attempting to click on the icon within a div element with role='button'. Despite trying to click on the icon, it does not function as expected.

Here is the corresponding HTML:

<div class="list">
  <div class="item">
    <div role="button" tabindex="-1">
      <strong>ItemName2</strong>
    </div>
    <div class="d">
      <div class="item-icon" role="button" tabindex="-1"  style="display: none">
        <i aria-label="icon: edit" class="edit"></i>
      </div>
    </div>
  </div>
  <div class="item"> ... </div>
  <div class="item"> ... </div>
  <div class="item"> ... </div>
</div>

And here is the JavaScript code snippet:

try {
    await driver.get("http://127.0.0.1");

    let findButtons = await driver.findElements(By.tagName('strong'));

    let buttons = findButtons.map(elem => elem.getText());
    const allButtons = await Promise.all(buttons);
    console.log(allButtons);             // It displays all button values, such as ItemName1
    let tButton;
    for (let i = 0; i < findButtons.length; i++) {
      if (allButtons[i] == 'ItemName2') {
        tButton = await findButtons[i];
        tButton.click();                // Trying to click on the button with value = ItemName2
        console.log(allButtons[i]);     // Displays button value 'ItemName2'    
      }
}}}

Console error message:

(node:12254) UnhandledPromiseRejectionWarning: StaleElementReferenceError: stale element reference: element is not attached to the page document

Answer №1

Encountering a stale element exception is likely due to attempting to access an element with outdated references. Each time the element is clicked within the loop, its reference gets updated making allButtons[i] ineffective. To resolve this issue, you need to obtain the most recent references of the buttons. Consider implementing the following solution:

JavaScript snippet:

const { By, Key, until } = require("selenium-webdriver");
const webdriver = require("selenium-webdriver");
require("chromedriver");
async () => {
  let driver = await new webdriver.Builder().forBrowser("chrome").build();
  try {
    await driver.get("http://10.203.201.77:8000/login");

    let findButtons = await driver.findElements(By.tagName('strong'));

    let buttons = findButtons.map(elem => elem.getText());
    const allButtons = await Promise.all(buttons);
    console.log(allButtons);             // Displaying all button values, for example, ItemName1
    let tButton;
    for (let i = 0; i < findButtons.length; i++) {
      buttons = findButtons.map(elem => elem.getText()); # updating the button to refresh element reference
      if (allButtons[i] == 'ItemName2') {
        tButton = await findButtons[i];
        tButton.click();                // Attempting to click on the button with value = ItemName2
        console.log(allButtons[i]);     //  Now showing button value as 'ItemName2'

      }
    }
      console.log("DONE");
    } catch (e) {
      console.log(e);
    } finally {
      await driver.quit();
    }
  }
}

Answer №2

Success! I have discovered the solution:

 const findButtons = await driver.findElements(By.tagName('strong'));

 const buttons = findButtons.map(async element => await element.getText()); // Enhanced with async & await
 const allButtons = await Promise.all(buttons);
 console.log(allButtons);   // This contains all item names       

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

Clicking on an element with ng-click does not impact the children of its parent

Why isn't this working as expected? I performed a field test. However, when I click on the <p> element inside child1, it doesn't have any impact on the <p> within child2. <div ng-init="test=false"> <div id="child1"&g ...

How can I exclude specific rows when using the get_where function in Codeigniter?

I'm developing a function that retrieves the 6 most recent events from the database. The objective is to determine if these events are related by a specific parameter (function already figured out), remove any duplicates from the array, and then add t ...

Loading Excel spreadsheet with points of interest and iterating through them

I am new to using DDT and I am attempting to save my test results in an excel file. The code is straightforward - it takes values from a ListArray, sends them to google.translate, captures the results, and adds them to another List. However, when looping ...

Decode: What steps are needed to obtain complete administrative access through coding?

As I create a cron job to update my Parse database, I encounter an issue where all documents are restricted by ACL permissions. Is there a method to override the ACL restrictions and grant my cron job full access similar to what I have on my Parse dashbo ...

What are the implications of not providing Content-Disposition in web security?

When allowing users to download files from my application, I manually set the "Content-Disposition" as "inline" or "attachment" depending on the file type. For example, I set it to "inline" for pdf files and "attachment" for html files. Is there a wa ...

Authentication using images

Has anyone successfully implemented an image-based authentication system using base64 encoded images in PHP or Java? I am curious to know if this is achievable, and if so, could someone provide a brief overview of how it can be done? I am really interest ...

Deciphering the intricacies of VUEX-STORE modules

Consider this scenario: I have two separate lists - one for income and one for outcome. Each list has its own storage, and I am adding these storages as modules in index.js. While I could create a single repository for both income and outcome, displaying ...

Is there a way to use the sort() function to further categorize objects that have been moved to the bottom of an array during sorting?

My task in JavaScript involves sorting within a single sort() function that is passed as a parameter. Specifically, I need to sort objects first by category and then further sort them by subcategory using: return item1.category.localeCompare(item2.catego ...

Tips for loading a webpage when a button is clicked with the help of jQuery AJAX and PHP:

Is it possible to dynamically load a page on button click, pass data to the new page using jQuery AJAX, and place the received value in an input field within the loaded page? Basically, the scenario is as follows: A button named "Something" triggers the l ...

Ways to identify if one object is positioned above another

So, here's the scenario: I'm trying to figure out how to detect when one element is positioned on top of another. Specifically, I'm dealing with SVG elements: <circle r="210.56" fill="#1ABCDB" id="01" priority="4" cx="658" cy="386">& ...

Filtering JSON Objects in JavaScript: A Comprehensive Guide

I have been attempting to filter the JSON object below and create an array of objects that have a value containing "steve" in the key 'markdown'. My initial approach involves converting the object to an array then applying a filter. Although I h ...

Passing a query variable to an input field through a PHP function

I have developed an autocomplete PHP function that connects to a MySQL database to fetch data based on user input: The PHP file is named search.php and contains the following code: if ( !isset($_REQUEST['term']) ) exit; $dblink = mysql_con ...

How can I properly type my object using generics if the Typescript code `let result: { [key: T[K]]: T } = {};` is not functioning as expected?

I am developing a function called keyBy that has a simple purpose. The objective of this function is to transform an array of objects into an object, using a provided 'key string': const arr = [{ name: 'Jason', age: 18 }, { name: &apo ...

typescriptWhat is the syntax in TypeScript for creating a prototype of a multidimensional

I'm currently working on implementing additional methods for a 2D array using TypeScript. Adding methods to a 1D array is straightforward, as shown below: interface Array<T> { randomize(); } Array.prototype.randomize = function () { ...

When the MATERIAL UI MENU ITEM is clicked, an action is triggered automatically upon loading the

I added an onClick event listener to a Menu Item in material UI, MUI. Upon loading the page, the onclick function triggers automatically. How can I resolve this issue? const [anchorEl, setAnchorEl] = useState(null) const open = Boolean(anchorEl) const ...

Can you explain the functions of Angular, Node.js, AJAX, and JQuery to me?

It's a real challenge for me to differentiate between the various frameworks, libraries, and APIs that I'm unfamiliar with, and understand how they are connected if at all. ...

Error: Unable to use map function on users .. cannot perform mapping on functions

Initially, the map function in my code was working fine. However, suddenly an error started appearing when I included the users.map line. Surprisingly, if I comment out that line, the code works perfectly again. Even more strangely, if I uncomment it, ev ...

Sending a JavaScript object to a JSP page via jQuery

I have an object in JavaScript var data = new Object(); It has attributes like: data.name = "mike"; data.id = 1; I am using jQuery to send this object to a JSP page var request = $.ajax ({ url: "test.jsp", type: "post", data: 'obj='+ dat ...

What are the best circumstances to utilize jQuery-UI autocomplete feature?

Looking for assistance in creating an input field that auto-populates user-entered values with database entries. Only values that exist in the database should be accepted. Could someone explain the advantages of using jQuery-ui autocomplete for this task ...

What steps should I take to retrieve the value from the daterange picker?

I am currently working on developing a user-friendly date range picker that can be used to select dates from a drop-down menu and pass them to an SQL query. At this stage, I am focused on handling the selected date and displaying it in an h1 tag. Options ...