Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change style height of div with JavaScriptExecutor Selenium Java

I have 'WebElement div' which represent my div:

<div style="width: 500px; height: 100px;">

I try to change height of my div like this:

JavascriptExecutor js = (JavascriptExecutor) driver;

WebElement div = ...;

js.executeScript("document[0].style.height = '200px'", div);

but doesn't work.

And this is exception I get:

org.openqa.selenium.WebDriverException: unknown error: Cannot read property 'style' of undefined

How I can change height of my div?

like image 306
KunLun Avatar asked Apr 19 '26 21:04

KunLun


2 Answers

document wouldn't be a valid selector here. You would want to do something like document.querySelector("div").style.height = "200px"

like image 110
connoraworden Avatar answered Apr 22 '26 11:04

connoraworden


You are passing div tag (WebElement) as an argument to executeScript method which will be passed on to JavaScript function to be executed, as per this doc.

So, you need to use below code (arguments[0]- first argument, instead of document[0]):

JavascriptExecutor js = (JavascriptExecutor) driver;

WebElement div = ...;

js.executeScript("arguments[0].style.height = '200px'", div);
like image 32
Viral Lalakia Avatar answered Apr 22 '26 12:04

Viral Lalakia