pranuta99
pranuta99

Reputation: 11

How to use selenium JavascriptExecutor to send text into a hidden text field whose ID is not known

I was dealing with a search input box icon which is clicked to open the input box. Since the icon is hidden I used JavaScriptExecutor to click on it and open the search input, like

WebElement searchBtn = driver.findElement(By.className("search-toggle"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript ("arguments[0].click();" , searchBtn);

But now, I need to enter some text into the input and ENTER to submit it. The solution would be to use the JavascriptExecutor again, like

JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById(**'gbqfq'**).value = 'search text';");

This time, the elementId 'gbqfq' is un known, right ? How do I go around this problem?

Upvotes: 0

Views: 2977

Answers (1)

Alexander Higgins
Alexander Higgins

Reputation: 6923

If you don't have the id then use another selector like By.Class or By.Xpath to find the element in selenium and use SendKeys to set the text or the equivalent JavaScript methods using .querySelector to find the element and using the value property to to set the text.

Upvotes: 1

Related Questions