Selecting and Identifying element with JQuery to use it in Selenium 2 Java API


This is the situation:

  • I use the Java API of Selenium 2 to open and control a firefox browser instance
  • I load the jQuery script to a page via JavaScript execution
  • I then use jQuery expressions to select elements and traverse through the DOM tree

Now is my question, can i somehow find a unique identifier for each of the found elements? My goal is to get the same element with Selenium by using an Xpath or CSS selector. So it would be most straighforward if i could generate an unambiguous selector for the elements in jQuery. Other ideas are welcome too.

I need an automatic approach for identifying elements in jQuery, which can be “converted” to Selenium elements / locators.


To make it clearer:

If i have selected an element in jQuery:

webDriver.executeScript("var element = $('#myDiv input.test')");

Now, I want something like this:

WebElement webElement = webDriver.executeScript("return element");

Is that possible?

  • You must to post comments

I found the solution, which is quite easy:

String jQuerySelector = "'#myDiv input.test'";
RenderedWebElement webElement = (RenderedWebElement) ((JavascriptExecutor) webDriver).executeScript("return $(" + jQuerySelector+ ").get(0);");

Working with an element in jQuery which was previosly selected in Selenium works too:

String jQuerySelector = "arguments[0]";
((JavascriptExecutor) webDriver).executeScript("return $(" + jQuerySelector+ ").doSomethingInJquery();", webElement);
  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.