How to check element is not visible in selenium

Sometimes, we need to verify whether an element is not displayed on a web page using Selenium. In Java, you can check this using the !element.isDisplayed() statement.

To handle dynamically loaded or delayed elements, it’s recommended to use explicit waits. While isDisplayed() itself does not throw an exception if the element exists, trying to locate an element that is not present in the DOM may throw a NoSuchElementException. Therefore, using a try-catch block or checking the element’s presence beforehand ensures your test handles such scenarios safely. We can also use findElements to verify whether an element is not displayed, which helps avoid exceptions like NoSuchElementException.

Below is an example demonstrating how to handle elements that are not displayed in Java, C#, and JavaScript.

Example Script for Element is Not Displayed:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.List;

public class ElementNotDisplayedExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

try {
// Wait for page load
wait.until((ExpectedCondition<Boolean>) wd ->
((String)((org.openqa.selenium.JavascriptExecutor) wd)
.executeScript("return document.readyState")).equals("complete"));

// Check if element exists
List<WebElement> elements = driver.findElements(By.id("myElement"));
if (elements.isEmpty() || !elements.get(0).isDisplayed()) {
System.out.println("Element is NOT displayed.");
} else {
System.out.println("Element is displayed.");
}

} catch (Exception e) {
System.out.println("Error while checking element visibility: " + e.getMessage());
} finally {
driver.quit();
}
}
}

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;

class ElementNotDisplayedExample
{
static void Main()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://example.com");

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

try
{
// Wait for page load
wait.Until(d =>
((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").ToString() == "complete"
);

// Check if element exists
IReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("myElement"));
if (elements.Count == 0 || !elements.First().Displayed)
{
Console.WriteLine("Element is NOT displayed.");
}
else
{
Console.WriteLine("Element is displayed.");
}
}
catch (Exception e)
{
Console.WriteLine("Error while checking element visibility: " + e.Message);
}
finally
{
driver.Quit();
}
}
}

const { Builder, By } = require('selenium-webdriver');

(async function elementNotDisplayed() {
let driver = await new Builder().forBrowser('chrome').build();

try {
await driver.get('https://example.com');

// Wait for page load
await driver.wait(async () => {
return await driver.executeScript('return document.readyState') === 'complete';
}, 10000);

// Check if element exists
const elements = await driver.findElements(By.id('myElement'));
if (elements.length === 0 || !(await elements[0].isDisplayed())) {
console.log("Element is NOT displayed.");
} else {
console.log("Element is displayed.");
}

} finally {
await driver.quit();
}
})();

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x