I am building a new test case and have ran into a new issue I am not sure how to get around. I need to click on an element that is both visiblity: hidden
and display: none
or at least need a way to execute the javascript function it calls. In the passed I have been able to use IJavascriptExecutor
to change an elements visibility or display but this option is no good for this test case as I am dealing with an array of elements that I locate at runtime using `Driver.FindElements' so I cannot get the exact selector to use my old method for changing display.
IJavaScriptExecutor js = (IJavaScriptExecutor)Driver;
var script = String.Format("document.querySelector('{0}').style.display='inline-block';", selector);
js.ExecuteScript(script);
Attached is a screenshot of the html and the css attributes for the element in question.
The way I see it I have two options I can make this test not dynamic and exercise the functionality on a single hardcoded element (yuck!), or I can figure out how to do this dynamically. So my hope (probably a fools hope) is that I can somehow call the onClick event bound to this button without actually clicking on it.
You could extract the onclick
attribute and send it as parameter. You also don't need to use IJavaScriptExecutor
, IWebDriver
extends this interface so you can just call ExecuteJavaScript method
IWebElement buttonToClick;
string script = buttonToClick.GetAttribute("onclick");
driver.ExecuteJavaScript<object>(script);
You can also try clicking it with JavaScript
driver.ExecuteJavaScript<object>("arguments[0].click();", buttonToClick);
It is possible to execute a JavaScript click on a IWebElement
via an IJavaScriptExecutor
, regardless of visibility.
Sounds like your issue stems from not being able to identify which element to click at runtime, I would take a look at XPaths.
In the meantime, here's an example of how to JavaScript click all <button>
elements with an onclick
event attribute, using an XPath:
IReadOnlyCollection<IWebElement> buttons =
Driver.FindElements(By.XPath(".//button[@onclick]"));
IJavaScriptExecutor js = (IJavaScriptExecutor)Driver;
foreach (IWebElement button in buttons)
{
js.ExecuteScript("arguments[0].click();", button);
}
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