Selenium JavascriptExecutor: Invalid or unexpected token

509 views Asked by At

When trying to use this format of selector with SeleniumJavascriptExecutor:

js.executeScript("arguments[0].textContent=${value}", driver.findElement(By.cssSelector('div.stb-LazyChosenDropdown div.tiles div.input:nth-child(1)')))

The following error is thrown:

org.openqa.selenium.JavascriptException: javascript error: Invalid or unexpected token

Yet it works without the :nth-child(1) part just fine so I'm inclined to think it doesn't like the (1) in the string which my IDE seems to think is an integer

3

There are 3 answers

0
pguardiario On BEST ANSWER

I can't tell what language that is but it should probably look like this:

js.executeScript("arguments[0].innerText = arguments[1]", element, value)
1
KunduK On

Try with nth-of-type(1) instead of nth-child(1)

js.executeScript("arguments[0].textContent=${value}", driver.findElement(By.cssSelector('div.stb-LazyChosenDropdown div.tiles div.input:nth-of-type(1)')))
1
undetected Selenium On

This cssSelector:

input:nth-child(1) 

selects the <input> element that is the first child of its parent can be replaced with:

input:first-child

which will also select the <input> element that is the first child of its parent.

Effectively the locator strategy will be:

driver.findElement(By.cssSelector('div.stb-LazyChosenDropdown div.tiles div.input:input:first-child'))