Check Visibility of Web Elements Using WebDriver Commands

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated May 9, 2025

How to check the visibility of web elements using various types of looping and conditional commands in WebDriver:

Previously in the series, we discussed WebDriver’s Select class which is primarily used to handle web elements like dropdowns and selecting various options under the dropdowns.

Moving ahead in the Selenium series, we will discuss the various types of looping and conditional commands in WebDriver like isSelected(), isEnabled(), and isDispalyed(). These methods are used to determine the visibility scope for the web elements.

Analyzing of Visibility Scope of Web Elements

Visibility of Web Elements Using Various Types WebDriver Commands

So let us start with a brief introduction – WebDriver has a W3C specification that details the information about the different visibility preferences based on the types of web elements upon which the actions are to be performed.

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels, etc.

  • isDisplayed()
  • isSelected()
  • isEnabled()

For an improved understanding, let us discuss the aforementioned methods with code examples.

As a specimen, we will use the “google.com” as an application under test and the “Learning_Selenium” project created in the previous tutorials for script generation.

Scenario to be automated:

  1. Launch the web browser and open the application under test – http://google.com
  2. Verify the web page title
  3. Verify if the “Google Search” button is displayed
  4. Enter the keyword in the “Google Search” text box by which we would want to make the request
  5. Verify that the “Search button” is displayed and enabled
  6. Based on the visibility of the Search button, click on the search button

WebDriver Code

Step #1: Create a new Java class named “VisibilityConditions” under the “Learning_Selenium” project.

Step #2: Copy and paste the below code in the “VisibilityConditions.java” class.

Below is the test script that is equivalent to the above-mentioned scenario:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class VisibilityConditions {
 
       /**
        * @param args
        */
 
       public static void main(String[] args) {
 
              // objects and variables instantiation
              WebDriver driver = new FirefoxDriver();
              String appUrl = "https://google.com";
 
              // launch the firefox browser and open the application url
              driver.get(appUrl);
 
              // maximize the browser window
              driver.manage().window().maximize();
 
              // declare and initialize the variable to store the expected title of the webpage.
              String expectedTitle = "Google";
 
              // fetch the title of the web page and save it into a string variable
              String actualTitle = driver.getTitle();
 
              // compare the expected title of the page with the actual title of the page and print the result
              if (expectedTitle.equals(actualTitle))
              {
                     System.out.println("Verification Successful - The correct title is displayed on the web page.");
              }
              else
              {
                     System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
              }
 
              // verify if the “Google Search” button is displayed and print the result
              boolean submitbuttonPresence=driver.findElement(By.id("gbqfba")).isDisplayed();
              System.out.println(submitbuttonPresence);
 
              // enter the keyword in the “Google Search” text box by which we would want to make the request
              WebElement searchTextBox = driver.findElement(By.id("gbqfq"));
              searchTextBox.clear();
              searchTextBox.sendKeys("Selenium");
 
              // verify that the “Search button” is displayed and enabled
              boolean searchIconPresence = driver.findElement(By.id("gbqfb")).isDisplayed();
              boolean searchIconEnabled = driver.findElement(By.id("gbqfb")).isEnabled();
 
              if (searchIconPresence==true && searchIconEnabled==true)
              {
                     // click on the search button
                     WebElement searchIcon = driver.findElement(By.id("gbqfb"));
                     searchIcon.click();
              }
 
              // close the web browser
              driver.close();
              System.out.println("Test script executed successfully.");
 
              // terminate the program
              System.exit(0);
       }
}

Code Walkthrough

Following are how we ascertain the presence of web elements on the web page.

boolean submitbuttonPresence=driver.findElement(By.id(“gbqfba”)).isDisplayed();

isDispalyed()

isDisplayed() is the method used to verify a web element within the webpage. The method is designed to result from a Boolean value with each success and failure. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.

Thus, the above code snippet verifies the submit button on the Google web page and returns a true value if the submit button is present and visible else returns a false value if the submit button is not present on the web page.

boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();

The method deals with the visibility of all kinds of web elements, not just limiting to anyone type.

isEnabled()

isEnabled() is the method used to verify if the web element is enabled or disabled within the webpage. Like isDisplayed() method, it results in a Boolean value with each success and failure. The method returns a “true” value if the specified web element is enabled on the web page and a “false” value if the web element is not enabled (state of being disabled) on the web page.

Thus, the above code snippet verifies if the submit button is enabled or not and returns a Boolean value depending on the result.

The isEnabled() method is significant in scenarios where we want to ascertain that only if “Condition A” is fulfilled, then the element(principally button) is enabled. Refer to the following illustration for the same.

Register

In the above figure, the Register button is enabled only when the agreement checkbox is selected.

Akin to the above methods, we have a method referenced as “isSelected()” which tests if the specified web element is selected or not.

boolean searchIconSelected = driver.findElement(By.id(“male”)).isSelected();

isSelected()

isSelected() is the method used to verify if the web element is selected or not. isSelected() method is predominantly used with radio buttons, dropdowns, and checkboxes. Analogous to the above methods, it is designed to result in a Boolean value with each success and failure.

Thus, the above code snippet verifies if the male radio button is selected or not and returns a Boolean value, depending on the result. Refer to the following image for the same.

Conclusion

In this tutorial, we tried to make you acquainted with the WebDriver’s looping and conditional operations. These conditional methods often deal with almost all types of visibility options for web elements.

Article Summary:

  • WebDriver has a W3C specification that details the information about the different visibility preferences based on the types of web elements.
  • isDisplayed() is the method used to verify the presence of a web element within the webpage. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.
  • isDisplayed() is capable of checking for the presence of all kinds of web elements available.
  • isEnabled() is the method used to verify if the web element is enabled or disabled within the webpage.
  • isEnabled() is primarily used with buttons.
  • isSelected() is the method used to verify if the web element is selected or not. isSelected() method is predominantly used with radio buttons, dropdowns and checkboxes.

Next Tutorial #15: While working on web applications, often we are re-directed to different web pages by refreshing the entire web page and re-loading the new web elements. At times there can be Ajax calls as well. Thus, a time lag can be seen while reloading the web pages and reflecting the web elements. Thus, our next tutorial in-line is all about dealing with such time lags by using implicit and explicit waits.

Note for the Readers: Till then, the reader can automate and test the visibility scope for the web elements using WebDriver’s methods.

Was this helpful?

Thanks for your feedback!

Recommended Reading

  • Selenium on Chrome

    In-Depth Tutorial On ChromeDriver for Running Selenium Webdriver Tests on Chrome Browser: Handling browser alerts while automating through Selenium will be discussed in this article. Moreover, we will elaborate on the set up of the Selenium script for the Google Chrome browser along with appropriate examples and pseudo-codes. Upon going…

  • Introduction To Selenium WebDriver

    Introduction to Selenium WebDriver: Earlier in this series, we published tutorials that focused more on Selenium IDE and its various aspects. We introduced the tool and discussed its features. We also constructed a few scripts using Selenium IDE and Firebug. From there, we moved on to different types of web…

  • Integration of Selenium with JMeter

    Overview: Hi Testers!! In this tutorial, you will learn a very interesting topic i.e. integrating your selenium scripts with JMeter and measuring the performance. Below are the topics covered in this session: Integrating Selenium with JMeter. Using WebDriver Sampler Plugin. => Click here for The Complete Free Training On JMeter…

  • Cucumber Java Selenium WebDriver Integration

    Cucumber Selenium WebDriver Java Integration with Example: In the last tutorial, we discussed the Cucumber tool, its usage, and different features. Moving ahead in our free Selenium online training series, we will discuss how to set up a cucumber project and will discuss the integration of Selenium WebDriver with Cucumber.…


READ MORE FROM THIS SERIES:



22 thoughts on “Check Visibility of Web Elements Using WebDriver Commands”

  1. When I tried to execute this tutorial with the original script as such:

    // verify if the “Google Search” button is displayed and print the result
    boolean submitbuttonPresence=driver.findElement(By.id(“gbqfba”)).isDisplayed();
    System.out.println(submitbuttonPresence);

    It yielded the following partial result log:

    Verification Successful – The correct title is displayed on the web page.
    Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element: {“method”:”id”,”selector”:”gbqfba”}

    A quick inspection of the page showed that the Google Search button was not using the ‘id’ property (they must have changed it), but it appears that they are using the ‘name’ property. So I modified the sample code, changing the search property and adding an identifying string to the result:

    // verify if the “Google Search” button is displayed and print the result
    boolean submitbuttonPresence=driver.findElement(By.name(“btnK”)).isDisplayed();
    System.out.println(“submitbuttonPresence:” + submitbuttonPresence);

    As you can see by the following partial result log, the Google Search button has now been correctly identified, but the script now fails on the next element:

    Verification Successful – The correct title is displayed on the web page.
    submitbuttonPresence:true
    Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element: {“method”:”id”,”selector”:”gbqfq”}

    This illustrates what has always been my biggest problem with Selenium. It seems the most common practice for scripting Selenium test programs is to capture web objects just before you need to make reference to them. This, in my never-to-be-humble opinion, is extremely poor practice for a couple reasons:

    1. If the identification for an on-screen object is changed by the developers (and it inevitably will change), you need to dig through the test script to find the object reference and change the search properties. Hopefully you edit the correct object reference.
    Hopefully you correct ALL the object references for this object.
    When the dev staff changes the UI again (which they will), you get to do it all over again!

    2. The test procedure you’re trying to execute is polluted with all this superfluous, garbage code that exists ONLY to find the stupid button (or whatever object) on the page! It has NOTHING to do with the actual test procedure being performed. This obscures the intention of the test program.

    Most of the purchased testing systems have some sort of object library function. In QTP it’s called the Object Repository (although HP rendered the function useless in version 10), and in TestComplete it’s called the NameMapping object. The purpose of such structures is
    to gather together all objects that test scripts will require, give them an easily identified reference name (What the heck is “gbqfba”?) in a sharable library. When the identification properties change for a given object, only one reference needs to be updated. If the
    logic of the function hasn’t changed, the test will continue to operate with no other revisions required.

    Similar functionality could (and I argue, it should) be implemented in Selenium, but I’ve never seen it scripted that way. I will never understand why not.

    Reply
  2. Hi Friends ,
    My self Kumar I am working as a functional tester in automation i have a problem while execute my programme it will not accept click option multiple times i don’t know any one can suggest me how to performe click operation multiple times.
    like i have a test case to check login functionality directly it will display pop up message username and password required then we mention username and again click on login it will display popup option enter password required but in my script it will accept only first login action second login option is not selected why in case any one try to understand resolve my issue

    Reply
  3. Hi everyone,

    if the example script is not working… which means we have to troubleshoot and correct it… I tried and figured out and made some changes to the script , its working..
    The changes are instead of web element locator By.id I used By.name.
    Hope it helps .. just copy and paste and run it…
    here is the working script for the above example:

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class VisibilityConditions {
    /**
    * @param args
    * @throws InterruptedException
    */
    public static void main(String[] args) throws InterruptedException {
    // objects and variables instantiation
    WebDriver driver = new FirefoxDriver();
    String appUrl = “https://google.com”;
    // launch the firefox browser and open the application url
    driver.get(appUrl);
    // maximize the browser window
    driver.manage().window().maximize();
    // declare and initialize the variable to store the expected title of the webpage.
    String expectedTitle = “Google”;
    // fetch the title of the web page and save it into a string variable
    String actualTitle = driver.getTitle();
    // compare the expected title of the page with the actual title of the page and print the result
    if (expectedTitle.equals(actualTitle))
    {
    System.out.println(“Verification Successful – The correct title is displayed on the web page.”);
    }
    else
    {
    System.out.println(“Verification Failed – An incorrect title is displayed on the web page.”);
    }
    // verify if the “Google Search” button is displayed and print the result
    boolean submitbuttonPresence=driver.findElement(By.name(“btnK”)).isDisplayed();
    System.out.println(submitbuttonPresence);

    // enter the keyword in the “Google Search” text box by which we would want to make the request
    WebElement searchTextBox = driver.findElement(By.id(“lst-ib”));
    searchTextBox.clear();
    searchTextBox.sendKeys(“Selenium”);
    Thread.sleep(1000);
    // verify that the “Search button” is displayed and enabled
    boolean searchIconPresence = driver.findElement(By.name(“btnG”)).isDisplayed();
    boolean searchIconEnabled = driver.findElement(By.name(“btnG”)).isEnabled();

    if (searchIconPresence==true && searchIconEnabled==true)

    {
    // click on the search button

    WebElement searchIcon = driver.findElement(By.name(“btnG”));

    searchIcon.click();

    }
    // close the web browser
    driver.close();
    System.out.println(“Test script executed successfully.”);
    // terminate the program
    System.exit(0);
    }
    }

    Reply
  4. all your artciles are so nice Shruti. Working great, My suggestion would be to include some assignments at the end of each tutorial.

    Reply
  5. Hai,

    I have this scenario
    In flipkart app i have selected brands as hp and dell for
    laptops and price i have selected in the range 25000 to 50000. i want to check whether the product has fall under between that range how to do that if i get more than 1000 product price?????
    if i want to compare all the values it will lead to to the performance issues….

    Reply
  6. in selenium webdriver, if i select dropdown value by ‘name'(eg. price low to high, high to low) then how do i verify that all products(GUI) are sorted by name or not?

    Reply
  7. Hi,

    I am automating searching functionality and then verifying if result is coming and asserting them by xpathofTheResult.isDisplayed function, but in some scenarios if no results returned then assertions is getting failed and my test is getting stopped.
    What I want to achieve is, if search results are appearing then show a message search result is appearing else show No result found. but code is breaking when xpath.isDisplayed is not visible (NoSuchElementException). How we can handle it?

    Reply
  8. Thanks a lot, it really means a lot for someone who really wanted to bring in selenium webdriver in practice without any prior knowledge. Really Helpful again thanks

    Reply
  9. I tried executing the above script but can see following error. Please help me to resolve this.

    Exception in thread “main” org.openqa.selenium.WebDriverException: f.QueryInterface is not a function
    Command duration or timeout: 31 milliseconds
    Build info: version: ‘2.44.0’, revision: ’76d78cf’, time: ‘2014-10-23 20:03:00’
    System info: host: ‘sys’, ip: ‘14.96.67.198’, os.name: ‘Windows 7’, os.arch: ‘x86’, os.version: ‘6.1’, java.version: ‘1.7.0_71’
    Session ID: 27771a7c-495b-4f26-8ff2-b97d3ab4d2b6
    Driver info: org.openqa.selenium.firefox.FirefoxDriver
    Capabilities [{platform=WINDOWS, acceptSslCerts=true, javascriptEnabled=true, cssSelectorsEnabled=true, databaseEnabled=true, browserName=firefox, handlesAlerts=true, nativeEvents=true, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=33.1}]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
    at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:304)
    at Selenium.VisibilityConditions.main(VisibilityConditions.java:19)
    Caused by: org.openqa.selenium.WebDriverException: f.QueryInterface is not a function
    Build info: version: ‘2.44.0’, revision: ’76d78cf’, time: ‘2014-10-23 20:03:00’
    System info: host: ‘sys’, ip: ‘14.96.67.198’, os.name: ‘Windows 7’, os.arch: ‘x86’, os.version: ‘6.1’, java.version: ‘1.7.0_71’
    Driver info: driver.version: unknown
    at .FirefoxDriver.prototype.get(file:///C:/Users/Kaku/AppData/Local/Temp/anonymous8799339024881419765webdriver-profile/extensions/[email protected]/components/driver-component.js:9504:13)
    at .DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/Kaku/AppData/Local/Temp/anonymous8799339024881419765webdriver-profile/extensions/[email protected]/components/command-processor.js:11635:16)
    at .DelayedCommand.prototype.executeInternal_(file:///C:/Users/Kaku/AppData/Local/Temp/anonymous8799339024881419765webdriver-profile/extensions/[email protected]/components/command-processor.js:11640:7)
    at .DelayedCommand.prototype.execute/<(file:///C:/Users/Kaku/AppData/Local/Temp/anonymous8799339024881419765webdriver-profile/extensions/[email protected]/components/command-processor.js:11582:5)

    Reply
  10. isDispalyed() METHOD DON’T RETURN FALSE IF ELEMENT IS NOT PRESENT ON WEB PAGE IT WILL HIT AN EXCEPTION
    dO YOU HAVE ANY OTHER WAY TO CHECK FOR VISIBILITY OTHER THAN USING isDispalyed() WITH TRY CATCH BLOCK WHICH WILL CATCH THE EXCEPTION.

    Reply
  11. Hi, guys. i just found that the ids used in this example are not up to date. i change the id references to name references in the below code it works correctly.

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class VisibilityConditions {

    public static void main(String[]args)
    {
    //objects and varaibles
    WebDriver driver = new FirefoxDriver();
    String appUrl= “https://google.com”;

    //launch the firefox browser and open the URL

    driver.get(appUrl);
    //maximize window
    driver.manage().window().maximize();

    //expected title
    String expectedTitle =”Google”;
    String actualTitle= driver.getTitle();
    //fetch title on the web site
    if (expectedTitle.equals(actualTitle))
    {
    System.out.println(“Verification successful – correct title displayed”);

    }
    else
    {
    System.out.println(“Verification Failed – An Incorrect title is displayed”);
    System.out.println(actualTitle);

    }
    //verify if the “google search button is displayed”
    boolean submitbuttonPresence=driver.findElement(By.name(“btnK”)).isDisplayed();
    System.out.println(submitbuttonPresence);

    //enter keyword in the “Google Search” text box
    WebElement searchTexbox = driver.findElement(By.id(“lst-ib”));
    searchTexbox.clear();
    searchTexbox.sendKeys(“Selenium”);

    //verify that the search button is displayed and enabled
    boolean searchIconPresence = driver.findElement(By.name(“btnK”)).isDisplayed();
    boolean searchIconEnabled=driver.findElement(By.name(“btnK”)).isEnabled();

    if (searchIconPresence==true && searchIconEnabled==true)

    {
    //click on search button

    WebElement searchIcon = driver.findElement(By.name(“btnK”));
    searchIcon.click();
    }

    //Close the browser

    driver.close();
    System.out.println(“Test script executed successfully.”);
    //terminate the program

    }
    }

    Reply
  12. # error is the above content . Isdisplayed() returns true if element is present( checks element is visible not hidden) if element is not present it will not return false . It will return NosuchElement found exception . It must be included in the try catch block

    public void deleteSubVar() throws Exception
    {
    try
    {
    if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
    {
    /**when the element is found do this*/
    }
    }
    catch(Exception e)
    {
    /**include the else part here*/
    }
    }

    Reply

Leave a Comment