How to set style display of an html element in a selenium test?

We can set the style display of an HTML element with Selenium WebDriver using JavaScript execution. The DOM interacts with page elements through JavaScript, and Selenium executes JavaScript commands using the executeScript method. This approach is particularly useful when you need to modify CSS properties like visibility, display type, or other styling attributes programmatically during test execution.

Some operations like setting the style display must be performed by JavaScript Executor. The getElementById method locates the element, then we apply the style.display property to set the display type such as block, none, inline, or flex.

Syntax

Following is the basic syntax for setting element style display using JavaScriptExecutor −

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("document.getElementById('elementId').style.display='displayType';");

Where elementId is the ID of the target element and displayType can be values like block, none, inline, inline-block, flex, etc.

Common Display Property Values

The CSS display property accepts various values for different layout behaviors −

Display Value Description
block Element takes full width and starts on a new line
none Element is completely hidden from view
inline Element flows with text, no line break
inline-block Inline flow but can have width and height
flex Element becomes a flex container

Method 1: Using getElementById

This method targets elements by their ID attribute, which is the most direct approach when the element has a unique ID −

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;

public class ElementStyleSet {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.tutorialspoint.com/index.htm");
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        
        // Javascript executor class with executeScript method
        JavascriptExecutor j = (JavascriptExecutor) driver;
        
        // set the display with style.display method
        j.executeScript("document.getElementById('gsc-i-id1').style.display='block';");
        
        driver.close();
    }
}

Method 2: Using WebElement Reference

This approach first locates the element using Selenium's standard methods, then passes it to JavaScript for styling −

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.JavascriptExecutor;

public class ElementStyleWebElement {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.tutorialspoint.com/index.htm");
        
        // Locate element using Selenium
        WebElement element = driver.findElement(By.id("gsc-i-id1"));
        
        // JavaScript executor
        JavascriptExecutor js = (JavascriptExecutor) driver;
        
        // Set display using element reference
        js.executeScript("arguments[0].style.display = 'none';", element);
        
        driver.quit();
    }
}

Method 3: Using CSS Selectors

For elements without IDs, you can use CSS selectors or XPath expressions within the JavaScript −

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ElementStyleSelector {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.tutorialspoint.com/index.htm");
        
        JavascriptExecutor js = (JavascriptExecutor) driver;
        
        // Using CSS selector
        js.executeScript("document.querySelector('.search-box').style.display = 'inline-block';");
        
        // Using class name
        js.executeScript("document.getElementsByClassName('header-logo')[0].style.display = 'flex';");
        
        driver.quit();
    }
}

Practical Example: Toggle Element Visibility

Following example demonstrates how to toggle an element's visibility during test execution −

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.JavascriptExecutor;

public class ToggleElementDisplay {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.tutorialspoint.com/index.htm");
        
        JavascriptExecutor js = (JavascriptExecutor) driver;
        
        // Hide element
        js.executeScript("document.getElementById('gsc-i-id1').style.display = 'none';");
        Thread.sleep(2000); // Pause to observe
        
        // Show element again
        js.executeScript("document.getElementById('gsc-i-id1').style.display = 'block';");
        Thread.sleep(2000); // Pause to observe
        
        driver.quit();
    }
}

Verifying Style Changes

You can also retrieve the current display value to verify that the style change was applied successfully −

// Get current display value
String displayValue = (String) js.executeScript("return document.getElementById('gsc-i-id1').style.display;");
System.out.println("Current display value: " + displayValue);

// Or check computed style
String computedDisplay = (String) js.executeScript("return window.getComputedStyle(document.getElementById('gsc-i-id1')).display;");
System.out.println("Computed display value: " + computedDisplay);
Setting Element Display with JavaScript Executor 1. Locate Element getElementById() CSS selector WebElement ref 2. JavaScript Executor executeScript() Pass JS command Execute on DOM 3. Apply Style style.display Set value 'block', 'none' Common Display Values: display = 'none' ? Hide element completely display = 'block' ? Show as block element display = 'inline' ? Show inline with text

Best Practices

  • Use WebElement references when possible, as they provide better error handling if the element is not found.

  • Add waits before executing JavaScript to ensure elements are loaded.

  • Verify changes by retrieving the computed style values after modification.

  • Handle exceptions when elements might not exist or be accessible.

  • Use meaningful display values appropriate for the element type and test scenario.

Conclusion

Setting the style display of HTML elements in Selenium tests is accomplished using JavaScript Executor's executeScript method. You can target elements by ID, CSS selectors, or WebElement references, then apply display properties like block, none, or inline. This technique is essential for controlling element visibility during automated testing scenarios.

Updated on: 2026-03-16T21:38:54+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements