Skip to content

Instantly share code, notes, and snippets.

@tomtheun
Created November 26, 2012 10:16
Show Gist options
  • Save tomtheun/4147513 to your computer and use it in GitHub Desktop.
Save tomtheun/4147513 to your computer and use it in GitHub Desktop.
Full implementation of a jQuery based Selenium CSS selector (in Java)
package nl.avisi.langur.testing;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.RemoteWebElement;
import java.util.List;
public class JQuerySelector extends By {
private final String jQuerySelector;
public JQuerySelector(String selector) {
this.jQuerySelector = selector;
}
@Override
public List<WebElement> findElements(SearchContext context) {
return (List<WebElement>) findWithJQuery(context, true);
}
@Override
public WebElement findElement(SearchContext context) {
return (WebElement) findWithJQuery(context, false);
}
private Object findWithJQuery(SearchContext context, boolean returnList) {
String getArgument = returnList ? "" : "0";
if (context instanceof RemoteWebElement) {
WebDriver driver = ((RemoteWebElement) context).getWrappedDriver();
return ((JavascriptExecutor) driver).executeScript("return $(arguments[0]).find('" + jQuerySelector + "').get(" + getArgument + ");", context);
}
return ((JavascriptExecutor) context).executeScript("return $('" + jQuerySelector + "').get(" + getArgument + ");");
}
@Override
public String toString() {
return "By.jQuerySelector: " + jQuerySelector;
}
}
@enepomnyaschih
Copy link

Great solution. See my update https://gist.github.com/enepomnyaschih/5847929

@irozaji
Copy link

irozaji commented Feb 8, 2019

can you please give an example for its usage ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment