Skip to content

JavaScript Error Element is null: while interacting ShadownDom element

I am writing code in Javascript to automate the website I have to use cookies when the user lands on the page for the first time

I am writing the following code to get cookies:

JavascriptExecutor js = (JavascriptExecutor)webdriver;
WebElement element= (WebElement) js.executeScript("return document.getElementById('usercentrics-root').shadowRoot.querySelector("[data-testid='uc-accept-all-button']");");

it locate element in browser correctly:

enter image description here

But In Intellij it gives me error:

java.lang.NullPointerException: Cannot invoke "" because "element" is null

enter image description here



If you are using Java create a browser instance and find elements:

System.setProperty("", "/path/to/chromedriver");           
WebDriver driver = new ChromeDriver(); 
WebElement WE = driver.findElementByCss("YourCSSSelector");;

If you are using JavaScript change your into:

WebElement element = (WebElement) js.executeScript
10 People found this is helpful