So I had a bit of trouble finding how to use JQuery to lookup stuff and pass it back to Selenium C#, but I got it working, so I thought I'd share what I've found.
In particular:
- How to pass IWebElements from C# to JQuery?
- How to get an array of objects back into C# from the results of the javascipt?
So I had a bit of trouble finding how to use JQuery to lookup stuff and pass it back to Selenium C#, but I got it working, so I thought I'd share what I've found.
In particular:
- How to pass IWebElements from C# to JQuery?
- How to get an array of objects back into C# from the results of the javascipt?
1 Answer
Reset to default 8Answering my own question here :)
You can pass webElements to the javascript and access them through arguments
.
To get the results back into C#, you have to cast to <IReadOnlyCollection<IWebElement>>
. For single elements, just use IWebElement
. One trick for multiple results is you have to call toArray
on the JQuery result, so that it returns a true array instead of an object.
var singleResult = Driver.ExecuteJavaScript<IWebElement>(
"return $('.my-class')[0]");
IWebElement elementToPass = Driver.FindElement(By.Id("cool-id"));
var results = Driver.ExecuteJavaScript<IReadOnlyCollection<IWebElement>>(
"return $(arguments[0]).children('.my-class').toArray()", elementToPass);