Home » Javascript » Selenium – Universal Way to Convert “WebElement” to Javascript or JQuery Object

Selenium – Universal Way to Convert “WebElement” to Javascript or JQuery Object

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a a simple WebElement and I want to perform a series(one or more) of JS/JQuery type actions on my object.

Most of the time this is easy, I simply get the ID of the object, pass that into the “ExecuteScript” function, and viola works great:

RemoteWebDriver driver = ...;
var element = driver.FindElementByXPath("..."); //Or any other type of lookup
driver.ExecuteScript(@"$('#" + element.GetAttribute("id") + "')."DoSomeStuff...;");

20% this doesn’t work at all because the item doesn’t have an ID. Of course there are many ways to lookup items in Selenium and many ways to lookup items in jQuery or Javascript, but they don’t always map, and while it may be possible to construct a query in jQuery that can lookup a Selenium object, that methodology cannot be the same for every object type.

Searching around it seems most people use the “id” method(Examples: 1, 2, 3). You can do this the opposite way. Another idea would be to give each element a unique ID in selenium before accessing it in jQuery, but it doesn’t look like that would work because to set it you need to using Javascript or jQuery.

I’ve yet to find a way to do this Universally for every element, how can this be done?

Answers:

You can, and always have been able to, pass element references back and forth in JavaScript via ExecuteScript. Whether those raw DOM elements can be converted to be used by JQuery is a matter upon which I am not qualified to speak. Nevertheless, the code for referencing a WebDriver-found element in your JavaScript code would be something like this:

// Assume element holds a reference to an already-found
// IWebElement, found using the standard WebDriver FindElement
// methods, and that driver is a properly-instantiated
// IWebDriver object.
// N.B., doing proper casting here, since it's idiomatic in
// the WebDriver library to code to the interface, not the concrete
// implementation.
IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
executor.ExecuteScript("alert(arguments[0].tagName);", element);

The above code will throw up an alert (and block your Selenium code), showing the element’s tagName JavaScript property. You can use this technique to use the element just as you would in JavaScript in the page.