Selenium JavaScript element to WebElement conversion

Submitted by Dickens A S on Sun, 04/10/2022 - 09:04

This article explains sometimes the HTML element of a browser will be beyond the visible rendered region.

In that case Selenium XPath which got by the findElement or findElements will less in number

Therefore we can combine javascript code and find those elements and cast it to WebElement

WebElement rootElement = driver.findElement(By.xpath("*//[@id='mydiv']");
javaScriptExecutor js = (javaScriptExecutor)driver;
List<WebElement> elements = (List<WebElement>)js.executeScript("return arguments[0].querySelectorAll('div');",rootElement);

In the above code rootElement is the visible element within which you want to find child elements

The querySelectorAll is executed on top of rootElement by using arguments[0] 

Then it gets type casted to List<WebElement>

The original type will be List<RemoteWebElement>

That's All :)

 

Selenium
JavaScript

Add new comment