How does Selenium isDisplayed() method work? | BrowserStack (2024)

Home Guide How does Selenium isDisplayed() method work?

By Sonal Dwivedi, Community Contributor - June 15, 2024

Selenium has been the number one choice for automation testers to test their web applications; and why not as it is open source, freely available, supports cross-browser, cross-platform and multiple programming languages. It offers numerous built-in methods that simplify automation tasks, saving valuable time.

Among these, the methods isDisplayed(), isSelected(), and isEnabled() of the WebElement interface are widely used to verify the presence of elements on a web page.

1. isDisplayed() in Selenium

The isDisplayed() method of WebElement interface is used to check whether the element is visible or not on the web page. It returns a boolean value true if the element is visible and false in either case.

Now if you are wondering how Selenium finds that a given element is visible or not, let me explain that as well. Selenium interacts with the DOM (Document Object Model) of the web page and when queried for isDisplayed(), it checks the element’s CSS properties like visibility, display and opacity to verify its visibility.

If the element has CSS property “visibility: hidden”, or “display: none” or opacity is set to 0 then Selenium considers it as not displayed and returns false and in either case it returns true.

For example, consider BrowserStack’s home page and open inspect element page.

How does Selenium isDisplayed() method work? | BrowserStack (1)

You may notice that the top bar element has style=”display: none;”. If you assert the isDisplayed() value for this element, it will return false.

import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;public class IsDisplayed { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.browserstack.com/"); WebElement nav=driver.findElement(By.cssSelector("nav.ds__top-bar")); boolean flag=nav.isDisplayed(); System.out.println("Nav element is displayed: " +flag); }}

How does Selenium isDisplayed() method work? | BrowserStack (2)

Similarly, to check the visibility of “Get Started” button in BrowserStack home page following is the code:

public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.browserstack.com/"); WebElement getStarted=driver.findElement(By.cssSelector("a#signupModalProductButton")); boolean flag=getStarted.isDisplayed();   System.out.println("Get Started button is displayed: " +flag); }}

How does Selenium isDisplayed() method work? | BrowserStack (3)

isDisplayed() method should be used in automation scripts to verify the presence of any web element on the web page before performing any action on it, such as clicking, sending keys, hovering, etc. Using this method ensures that the automation script is interacting with the visible elements only and thus reduces flaky results or false negatives.

2. isSelected() in Selenium

The isSelected() method in Selenium also belongs to the WebElement interface which is used to determine if a web element such as radio button or checkbox is selected or not. It returns a boolean value as true if the web element is selected and false if it is not selected.

Automating web forms is one of the common and typical scenarios which involves clicking radio buttons, checkboxes and selecting an option from drop-downs. And before selecting any radio button or checkbox it is necessary to check the current state of the element as being selected or not. For example, consider a use case which says to select a radio button.

In case if it is already selected; then selecting the radio button will actually deselect the radio button and hence doing the reverse of what was expected. To avoid such mistakes, it is always better to check the current state of the web element before selecting/ deselecting it.

Below code demonstrates how to find the isSelected value for a radio button before and after selecting using W3Schools.com.

public class IsSelected { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio"); driver.switchTo().frame("iframeResult"); Thread.sleep(2000); WebElement htmlRdBtn=driver.findElement(By.cssSelector("input#html")); //isSelected() value before selecting radio button boolean flag=htmlRdBtn.isSelected();    System.out.println("HTML radio button is selected: " +flag); htmlRdBtn.click(); //isSelected() value after selecting radio button boolean flag1=htmlRdBtn.isSelected();    System.out.println("HTML radio button is selected: " +flag1); }}

How does Selenium isDisplayed() method work? | BrowserStack (5)

3. isEnabled() in Selenium

isEnabled() method is a built-in method provided by Selenium’s WebElement interface to determine whether the web element is enabled or disabled on a web page. It returns a boolean value true if the element is enabled or false in either case. When a web element is disabled, it appears grayed out and non-interactive as it cannot receive any user actions such as clicking, selecting or typing.

isEnabled() method can help in automation by asserting the state of the element before performing any user action on it. Which means that before performing any event on the web element it is recommended to verify the state of the web element as enabled or disabled to avoid exceptions in the script.

Below code demonstrates how to find the isEnabled value for a button using W3Schools.com.

Navigate to https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_pushbutton_disabled2, open inspect element window and observe that “My Button” has no attribute as enabled=false or disabled and hence it is enabled.

How does Selenium isDisplayed() method work? | BrowserStack (6)

Next, click on the “Try It” button and then check the status of the “My Button”. Below code demonstrates the same.

public class IsEnabled { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver();  driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_pushbutton_disabled2"); driver.switchTo().frame("iframeResult"); Thread.sleep(2000); WebElement myBtn=driver.findElement(By.cssSelector("button#myBtn")); //isEnabled() value before clicking try it button boolean flag=myBtn.isEnabled();  System.out.println("My Button is enabled: " +flag); WebElement tryBtn=driver.findElement(By.xpath("//button[text()='Try it']")); tryBtn.click(); //isEnabled() value after clicking try it button boolean flag1=myBtn.isEnabled();  System.out.println("My Button is enabled: " +flag1); }

How does Selenium isDisplayed() method work? | BrowserStack (7)

Comparison between isDisplayed(), isSelected() & isEnabled()

Here’s the difference between isDisplayed(), isSelected() and isEnabled() in Selenium:

MethodPurposeSyntaxReturn valueWhen to Use
isDisplayed()Determines the visibility of the web elementboolean isDisplayed()true if element is visible, false if not visibleIt is used to check the visibility of web elements before performing any action on it
isSelected()Determine if the web element is selected or notboolean isSelected()true if element is selected, false if not selectedIt is used to check the status of checkbox, radio buttons or drop downs before performing any action on it
isEnabled()Check if the web element is enabledboolean isEnabled()true if element is enabled, false if disabledIt is used to check the state of the web element as enabled or disabled before performing any action on it

Why use BrowserStack Automate for Selenium Tests?

Here’s why you should run your Selenium Tests on Real Devices and Browsers using BrowserStack Automate:

  • Parallel Testing: Parallel testing is paramount in reducing overall execution time as it allows testers to execute scripts simultaneously on multiple devices/browsers. Automate platform provision this feature by giving access to latest devices and browsers for the testers to test their applications.
  • Real devices and browsers: A genuine user experience can only be achieved after testing the applications on real devices and browsers. Testing on emulators and simulators can be easy, however it may not give accurate test results at all times with respect to functional and even non-functional testing such as application’s performance.
  • Dedicated Dashboard: After running Selenium test cases on Automate product, it creates a report in a dashboard which can be referred to manage and monitor the automation testing activities. It includes an overview of the testing status as Pass/Fail/Pending with all the environment details such as device name, OS version, Platform, browser name, browser version, test execution time and duration, screenshots, etc.
  • Custom Reports with Artifacts: In Automate, custom reports can be generated to provide detailed and customized reports for the automated test execution. With this feature it allows to customize the structure and content of the report as per user’s need. It can include a vast range of test data such as test execution status, device and browser configurations, test duration, video recording, screenshots, etc.
  • Easy Integration with CI/CD Pipeline: Automate can be easily integrated with popular CI/CD tools such as Jenkins, TeamCity, TravisCI. The team can achieve faster delivery cycles with great confidence in the reliability, performance and compatibility of the application across different devices and platforms.

Talk to an Expert

How does Selenium isDisplayed() method work? | BrowserStack (2024)

FAQs

How does Selenium isDisplayed() method work? | BrowserStack? ›

isDisplayed() in Selenium

How does isDisplayed work in Selenium? ›

In Selenium, the isDisplayed() method is pivotal for web testing, determining if web elements are visible or hidden. This method checks an element's CSS properties for visibility and returns a boolean: true if visible, false if hidden or absent in the DOM.

What is the difference between isDisplayed () and isEnabled () functions in Selenium WebDriver? ›

Boolean isDisplayed(): This method determines if an element is displayed or not. It returns true if the element is displayed and false if it is not. Advantage of this method is that it avoids parsing an elements style attribute. Boolean isEnabled(): This method determines if an element is enabled or not.

What is the difference between isDisplayed and isVisible? ›

isVisible is a method of the old Selenium RC and isDisplayed is a method of Selenium 2. An element can be rendered invisible by setting the CSS visibility property to hidden or the display property to none , either for the element itself or one if its ancestors. This method will fail if the element is not present.

How to assert isDisplayed in Selenium? ›

The syntax for isDisplayed method in Selenium is as follows: <webdriver instance>. <method to find element>(<property used>(<property symbol>)). isDisplayed();

What is the output of the isDisplayed method? ›

The isDisplayed() method of WebElement interface is used to check whether the element is visible or not on the web page. It returns a boolean value true if the element is visible and false in either case.

What is the difference between isPresent and isDisplayed? ›

isDisplayed resolves to whether the element is visible or not, but throws an exception if it is not in the DOM. isPresent resolves to whether it is there in the DOM or not, regardless of whether it is actually visible or not. It doesn't throw an exception.

What are possible ways to refresh a page in Selenium? ›

How to Refresh Page using Selenium C#?
  1. Using the Navigate(). Refresh() command.
  2. Using the Navigate(). GoToUrl() using the current page URL.
  3. Simulating the keypress for the F5 key.
Jan 6, 2023

What is the difference between getWindowHandles () and getWindowHandle () in Selenium? ›

getWindowHandles() – It stores the set of handles for all the pages opened simultaneously. driver. getWindowHandle() – It fetches the handle of the web page which is in focus. It gets the address of the active browser and it has a return type of String.

How can we enter text without using send keys? ›

There are a few alternative ways to type or input text in Selenium without using the sendKeys() method: JavaScript Executor: You can use JavaScriptExecutor to execute JavaScript code that sets the value of an element directly.

What is the difference between isDisplayed and isExisting? ›

isExisting is different from isDisplayed — isDisplayed checks for the visibility of the element while isExisting checks that the element is present. For example, you can have an element present, but it may have the hidden clause on it.

What is the difference between visibility none and display hidden? ›

Difference between display:none and visiblity: hidden

visibility:hidden hides the element, but it still takes up space in the layout. display:none removes the element from the document. It does not take up any space.

What is the difference between visibility and IsVisible? ›

Determination of the IsVisible value takes all factors of layout into account. In contrast, Visibility, which is a settable property, only indicates the intention to programmatically make an element visible or invisible.

What is the difference between isDisplayed and isEnabled in WebDriver? ›

2) Boolean isDisplayed(): This method determines if an element is displayed or not. It returns true if the element is displayed and false if it is not. The advantage of this method is that it avoids parsing an element's style attribute. 3) Boolean isEnabled(): This method determines if an element is enabled or not.

How to check if an element is selected or not in Selenium? ›

isSelected() Method in Selenium

The isSelected() method checks that if an element is selected on the web page or not. It returns a boolean value (true) if selected, else false for deselected.

How to verify if an element is displayed on screen in Selenium? ›

How can you find whether an element is displayed on the screen using Selenium? The is_displayed() method of the WebElement class can be used to determine whether an element is displayed on the screen. This method returns a boolean value indicating whether the element is currently visible on the page.

How does Selenium check all dropdown values? ›

We can extract all the options in a dropdown in Selenium with the help of Select class which has the getOptions() method. This retrieves all the options on a Select tag and returns a list of web elements. This method does not accept any arguments.

How to handle hidden pop up in Selenium? ›

Handling Web Dialog Box/Popup Window using Selenium

In Selenium, a robot class is used to handle the keyboard and mouse functions. It is used to close the pop-up window. You can get the window handle of the pop-up window using the WindowHandle() function.

Top Articles
Lessons learned: Urban charter schools demonstrate potential to improve student performance
Cronos Wallet (CRO) | Secure CRO Wallet
Jack Doherty Lpsg
Tyler Sis 360 Louisiana Mo
Craigslist Home Health Care Jobs
Angela Babicz Leak
Algebra Calculator Mathway
1970 Chevelle Ss For Sale Craigslist
Lighthouse Diner Taylorsville Menu
Chase Bank Operating Hours
How do you mix essential oils with carrier oils?
Tiraj Bòlèt Florida Soir
Www.paystubportal.com/7-11 Login
ATV Blue Book - Values & Used Prices
Brutál jó vegán torta! – Kókusz-málna-csoki trió
Hartford Healthcare Employee Tools
C Spire Express Pay
Beau John Maloney Houston Tx
Aspen.sprout Forum
2015 Honda Fit EX-L for sale - Seattle, WA - craigslist
Aldi Sign In Careers
Obsidian Guard's Cutlass
Ruse For Crashing Family Reunions Crossword
Espn Horse Racing Results
1973 Coupe Comparo: HQ GTS 350 + XA Falcon GT + VH Charger E55 + Leyland Force 7V
[PDF] PDF - Education Update - Free Download PDF
How To Tighten Lug Nuts Properly (Torque Specs) | TireGrades
Bra Size Calculator & Conversion Chart: Measure Bust & Convert Sizes
Infinite Campus Asd20
FSA Award Package
Puffin Asmr Leak
Bad Business Private Server Commands
Taktube Irani
Aid Office On 59Th Ashland
Ofw Pinoy Channel Su
Roch Hodech Nissan 2023
Beth Moore 2023
The 38 Best Restaurants in Montreal
Elizaveta Viktorovna Bout
Hellgirl000
Conroe Isd Sign In
Man Stuff Idaho
Atom Tickets – Buy Movie Tickets, Invite Friends, Skip Lines
Tripadvisor Vancouver Restaurants
Ladyva Is She Married
Pike County Buy Sale And Trade
Sandra Sancc
Dagelijkse hooikoortsradar: deze pollen zitten nu in de lucht
Westport gun shops close after confusion over governor's 'essential' business list
Greg Steube Height
Raley Scrubs - Midtown
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6422

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.