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

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


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);


Using eval makes it even easier. Use an index selector such as [0] with the jQuery code or it will return a collection of elements.

    String elementLocator = "$('#btnID')[0]";    public RemoteWebElement getElementByJQueryLocator(String jQueryLocator){        JavascriptExecutor js = (JavascriptExecutor) driver;        RemoteWebElement element = (RemoteWebElement) js.executeScript("return eval(arguments[0]);", jQueryLocator);        return element;    }        RemoteWebElement webElement = getElementByJQueryLocator(elementLocator);        webElement.click();


Not sure of your exact problem but you can build you locator using html id, name, class etc attributes.