Hi I would like to know how to click on hidden element and/or disable element by using Selenium WebDriver.
I know with selenium 1 I can do this as below:
selenium.click(id="idOfHiddenField");
and this would work, but with selenium 2 (WebDriver), this doesn't. I do not want to use jquery to enable or show hidden fields , or JavaScript. This is because most of the test are using xpath.
Or do I just have to stay with old selenium which allows you to click on hidden fields?
Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method.
WebElement hiddenDiv = seleniumDriver. findElement(By.id("hidden_div")); String n = hiddenDiv. getText(); // does not work (returns "" as expected) String script = "return arguments[0]. innerText"; n = (String) ((JavascriptExecutor) driver).
First Solution: Try to write unique XPATH that matches with a single element only. Second Solution: Use Explicit wait feature of Selenium and wait till the element is not visible. Once it is visible then you can perform your operations.
There is a easier way to work around the problem using JavascriptExecutor
.
For example:
document.getElementsByClassName('post-tag')[0].click();
The above javascript would click on the "Selenium" tag on the top right of this page (next to your question), even if it were hidden (hypothetically).
All you need to do is issue this JS instruction via the JavascriptExecutor
interface like so:
(JavascriptExecutor(webdriver)).executeScript("document.getElementsByClassName('post-tag')[0].click();");
This would use the JS sandbox and synthetic click event to perform the click action. Although it defeats the purpose of WebDriver user activity simulation, you can use it in niche scenarios like in your case to good effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With