Skip to content

Instantly share code, notes, and snippets.

@enepomnyaschih
Forked from tomtheun/JQuerySelector.java
Last active February 8, 2019 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enepomnyaschih/5847929 to your computer and use it in GitHub Desktop.
Save enepomnyaschih/5847929 to your computer and use it in GitHub Desktop.
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(selector, true);
}
public JQuerySelector(String selector, boolean visible) {
this.jQuerySelector = selector + (visible ? ":visible" : "");
}
@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('" + escape(jQuerySelector) + "').get(" + getArgument + ");", context);
}
return ((JavascriptExecutor) context).executeScript("return $('" + escape(jQuerySelector) + "').get(" + getArgument + ");");
}
@Override
public String toString() {
return "By.jQuerySelector: " + jQuerySelector;
}
private String escape(String s) {
return s.replace("'", "\\'");
}
}
@enepomnyaschih
Copy link
Author

For front-end tests, it is reasonable to work with elements which are visible to user, by default.

@tomtheun
Copy link

I like the visibility addition, changed it in our own codebase!

@codeomnitrix
Copy link

What would happen if Jquery is not included in the Application.

@RickCollier
Copy link

if jquery is not included with the application you have to inject it somehow.

https://gist.github.com/djangofan/7677995

one method also in java. I just used this and it works. There is also apparently a method to have selenium inject it as a user extension.

@Automationer
Copy link

Please write an example code for how this class can be used.
thanks

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