SkipKent
SkipKent

Reputation: 457

I need Selenium JavascriptExecutor to return an element via jquery

I am at my wits end with this and I'm sure the answer is simple but I just can't figure it out.

I've got a jquery selector that finds and element perfectly when I put this in the console of google Chrome:

$(".answer__label:contains('Yes')")

Now I want to use this to retrieve an element in a WebDriver test, so I'm using JavascriptExecutor in the following way:

private WebElement findByJSText(String text) {
    String script = String.format("return ('.answer__label:contains('%s')')", text);
    WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript(script);
    return element;
}

This gives the error, "missing ) in parenthetical". I've seen references to this error all over, but none that seem to apply to my situation.

How do I massage this to return the element properly?

(please don't respond telling me to use driver.findElement(By.linkText), thanks)

ADDENDUM

Here's what my final working method looks like:

private WebElement findByJSText(String text) {
    //String script = String.format("return $('.answer__label:contains('%s')')", text);
    String script = String.format("return $(\".answer__label:contains('%s')\")[0]", text);
    WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript(script);
    return element;
}

I may add a 2nd parameter for a css string to make this more flexible.

Thanks all for the help!

Upvotes: 2

Views: 5197

Answers (1)

Ant's
Ant's

Reputation: 13811

In this line:

String script = String.format("return ('.answer__label:contains('%s')')", text);

Your javascript code is error, where is the jquery $ function? Correct js code should be:

String script = String.format("return $('.answer__label:contains('%s')')", text);

Edit:

You have the ' within another '. Thats the problem, I tried the following js code and its working fine for me:

String script = String.format("return $(\".answer__label:contains('%s')\")", text);

Upvotes: 3

Related Questions