I encounter an error if an element is not displayed when using the isDisplayed() method

My situation

  1. Going to a specific page
  2. Should I click the element that is displayed
  3. If the element is not displayed, just ignore it

My function

exports.checkButton = function (driver) {

    driver.findElement(By.css(".btn.btn-danger.pull-right.remove-promotion")).then(function(button){ 

        if (button.isDisplayed()) {

            console.log("The element is displayed"); 

    } else { 

            console.log("The element is not displayed");

    }
});

My issue

When the element is not displayed, the message

console.log("The element is not displayed");
is not showing up and I'm getting an error:

Uncaught NoSuchElementError: no such element: Unable to locate the element: {"method":"css selector","selector":".btn.btn-danger.pull-right.remove-promotion"}

Answer №1

isDisplayed() is a method that can only be used when the element is present in the document object model (DOM) but is hidden, for example, if it has a style of display: none. It seems that in your situation, the element does not exist in the DOM when it is not being displayed, which is why you are encountering the NoSuchElementError exception.

Here is a suggested approach:

export.checkButton = function (driver) {    
        driver.findElement(By.css(".btn.btn-danger.pull-right.remove-promotion")).then(function(button){ 
            console.log("Element is displayed");
            button.click();
            return true;
        }).catch(function (ex) {
            console.log("Element is not displayed");
            return false;
        });
}

var display = checkButton(driver);
while (display) {
    display = checkButton(driver);
}

It is recommended to examine the behavior of the DOM in both scenarios - when the element exists and when it does not exist.

Answer №2

Ensuring that an element is visible on the screen requires first confirming its existence within the Document Object Model (DOM). In Java, this can be achieved using the following method:

public boolean isElementPresentInDom(By by) {
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
    boolean isElementPresent = (driver.findElements(by).size() != 0);
    driver.manage().timeouts().implicitlyWait(driverTimeOut, TimeUnit.MILLISECONDS);
    return isElementPresent;
}

(The equivalent in Javascript may vary slightly, but the concept remains consistent.) If the method returns true, it indicates that the element is present and can be checked for visibility.

Answer №3

When using the .isDisplayed() method, it is important to remember that it assumes the element already exists. If you are encountering an error, it could be due to the element not actually existing on the page. This could be caused by an incorrect locator or possibly the element has not finished loading. To address this, consider using .findElements() (note the plural form) and check that the size is greater than 0 to confirm the element's existence. It is recommended to encapsulate this logic within a function so it can be easily reused when needed. Once you have confirmed the element's existence, then proceed to check its visibility with .isDisplayed(). By following these steps, you can ensure that your code runs smoothly.

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

Recommendations for a UI library specializing in displaying analytical graphs

Looking to create analytical graphs of tweets similar to the site found at the following link Website-Link Curious about the top open source options available for this task? I've heard good things about Raphael.js. Any other recommendations? ...

Storing a child in an existing object with Firebase and Angular 6

How can I save a new form to an existing list with the following code snippet: createNewTumeur(newTumeur: Tumeur) { this.tumeurs.push(newTumeur); const id: string = this.route.snapshot.params['id']; firebase. ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

Conceal a child div through the use of AJAX technology

Utilizing AJAX, I am loading pages on my website. Each page consists of two common div elements - the header div and the content div. When navigating from one page to another, I load the content div of the next page into the current page using the followin ...

Feeding information into a React component within a pre-existing application

I currently have a PHP application that is responsible for managing products, each of which can have multiple images associated with it. The process of adding or removing images is currently handled server-side with PHP, resulting in a page load for each a ...

Issue encountered while attempting to delete dynamically added fields

I'm facing an issue where I am adding 3 fields dynamically (2 text fields and 1 remove button). The add button is functioning correctly, but the problem arises with the remove function. Currently, it only removes the remove button itself and not the o ...

Link that causes the regular expression test to hang

My goal is to create a regular expression that can accurately identify URLs. I found the code snippet for this on Check if a Javascript string is a url. The code looks like this: function ValidURL(str) { var pattern = new RegExp('^(https?:\/&b ...

What is the best way to ensure that this form field remains hidden when the page is loaded?

In my Django project, I have a form that should only display the entity name on page load. However, it is currently showing both the entity name and quote text fields. The quote text field should only be visible when the entity name is not in the database. ...

JS if clause fails to return true as expected

Here is my setup: <div id="user_input">...</div> And a button: <input type="button" id="panel_button">...</button> Using a selector: function $(id) { return document.querySelector(id); } With an event handler: var button_ ...

Encountering a java.net.SocketException error with Selenium when attempting to call driver.quit() resulting in a

After browsing through these threads: java.net.SocketException: Connection reset on Selenium driver.close() or driver.quit() statements selenium/java- java.net.SocketException: Connection reset I am still puzzled by the issue at hand. Everything seems t ...

The Integration of Google Books API with Ajax Technology

When a user enters an ISBN number in the search box, it triggers a display of information from the Google Books API within a div. This information is fetched from a JSON file in the standard format and includes details like title, subtitle, author, and des ...

`Is there a specific location for this code snippet?`

Recently, I stumbled upon a script that enables website screen scraping. For instance, you can check out an example on JsFiddle The issue arises when I attempt to incorporate another script from "Embed.ly" This specific script enhances a provided link and ...

JavaScript - An unexpected error occurred: Syntax error, unrecognized expression: [href=#contact] (WordPress)

I am currently working on a feature that involves adding a class to a specific menu item when a certain section is in view. However, I encountered an error that reads: Uncaught Error: Syntax error, unrecognised expression: [href=#contact] Your help would ...

Guide to adding a Scrollable Navbar

Is the term "scroll bar" really accurate? I want to create a scrollable feature where users can easily select a city using their mouse wheel (or swipe on a smartphone) and then choose from possible cities within that country in a second window. Something s ...

Exploring the possibilities of JQuery for smoothly transitioning to internal link destinations?

As a newcomer to JQuery, I have implemented internal links on my website and have a question. Is there a way to create a smooth 'slide down' effect when a user clicks on an internal anchored link text to navigate to the link destination? < ...

Creating an executable from a test file located in a separate directory within the current folder

I am facing an issue with compiling a test file in Java with the files Triangle.java and TriangleTest.java located in different folders. The directory structure is set as C:\Users\A\Desktop\NewPrograms, organized into separate folders f ...

Encountering difficulties accessing the array in the controller through ajax

Having trouble receiving an array of data from AJAX to the controller. $.ajax({ type: "POST", url: "/Home/List", traditional: true, contentType: 'application/json', data: { "Query&quo ...

The message sent from the server via SocketIO seems to be malfunctioning

Currently, I am in the process of developing an application that utilizes websockets for facilitating server-client communication. The main idea behind this concept is to enable the client to request messages from the server, while also allowing the server ...

Managing iframe scrolling using the parent window's scrollbar

I am currently working on an iframe to be utilized across various domains. The functionality of this iframe involves displaying a data list that updates when the bottom of the scroll is reached. An issue I encountered is that the parent window, where the ...

Whenever I try to import a directory that contains modules, Webpack encounters an error

I am currently in the process of developing a small npm library to streamline API interaction. Here is an overview of my folder structure... dist/ index.js src/ index.js endpoints/ endpoint1.js package.json webpack.config.js Inside my src/index ...