Ripon Al Wasim
Ripon Al Wasim

Reputation: 37816

How to click a button in Selenium WebDriver with Java using jQuery

I have the following HTML:

<button class="gbqfba" name="btnK" aria-label="Google Search" id="gbqfba"><span id="gbqfsa">Google Search</span></button>

My following code for clicking "Google Search" button is working well using java in WebDriver:

driver.findElement(By.id("gbqfb")).click();

I want to use jQuery with WebDriver to click the button. How can I do it?

I did the following (Test was run in eclipse by using TestNG framework):

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("$('#gbqfba').click();");

Unfortunately the following error was displayed:

org.openqa.selenium.WebDriverException: $ is not defined (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 23 milliseconds

What's the wrong with my above code?

Upvotes: 2

Views: 12911

Answers (3)

Santhosh Raja
Santhosh Raja

Reputation: 11

This could also be solved using List of classes

List w = driver.findElements( By.cssSelector("button.gbqfba"));

    for(WebElement s1: w)
    {
        String s2= s1.getText();
        System.out.println(s2);

        if(s2.contentEquals("Google Search"))
        {
            s1.click();   
            break;
        }
    }

Upvotes: 0

Ripon Al Wasim
Ripon Al Wasim

Reputation: 37816

The following code works nicely:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
URL jqueryUrl = Resources.getResource("jquery-1.8.2.min.js");
String jqueryText = Resources.toString(jqueryUrl, Charsets.UTF_8);
jse.executeScript(jqueryText);
jse.executeScript("$('#gbqfba').click();");

Upvotes: 1

oshea00
oshea00

Reputation: 181

WebDriver doesn't apparently use jQuery extension, so '$' isn't in the name space. You could load the minified jQuery.js into a string, then eval it as part of your test - which would add '$' to page's namespace...

Upvotes: 1

Related Questions