Using javascriptExecutor & JQuery to click WebElement

3,244 views
Skip to first unread message

Danny Guerrier

unread,
Jun 3, 2011, 5:45:43 PM6/3/11
to webd...@googlegroups.com
I along with many others I assume are having issues where WebElement::click() is not triggering the onClick event for many javascript heavy web applications.

Can anyone tell how to maybe find an element in the usual fashion then use the JavascriptExecutor to click on the element; preferably using JQuery?

Thanks

Luke Inman-Semerau

unread,
Jun 4, 2011, 3:16:36 PM6/4/11
to webd...@googlegroups.com
Code below is in Java, but very similar for most bindings...

//if you need to load jquery to the page
((JavascriptExecutor) driver).executeScript("var s=document.createElement('script');s.src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';document.body.appendChild(s);");

//Get your element
WebElement el = driver.findElement(By.something("..."));
el.click(); // really should work, if not we probably should log a bug with sample html/js to reproduce the issue
// this is what you're asking for...
((JavascriptExecutor) driver).executeScript("$(arguments[0]).click()", el);

I tried testing this locally and it would not click on an anchor tag (<a href="javascript:alert('clicked a');">) but would click it if it used the onclick (<a id="a1" href="javascript:alert('a1 clicked');" onclick="alert('onclick a')">a</a>). If your page is really javascript heavy, then the onclick is being attached to the element by javascript and this should work for you, if it does I'd love to see it reproduced that WebElement.click doesn't work and the jquery.click does work.

--
You received this message because you are subscribed to the Google Groups "webdriver" group.
To post to this group, send email to webd...@googlegroups.com.
To unsubscribe from this group, send email to webdriver+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/webdriver?hl=en.

BrieBug

unread,
Jun 4, 2011, 11:19:53 AM6/4/11
to webdriver

I have seen this as well where I attempt to click on an element and
the page just scrolls to the bottom instead of processing the click
event.

In those cases, I have handled it with this code:

var script = "$('input#myButton').trigger('click')",

((IJavaScriptExecutor)WebDriver).ExecuteScript(script);

Hopefully this helps you...

Jesse

Rostislav Matl

unread,
Jun 6, 2011, 10:53:32 AM6/6/11
to webdriver
I have solution that does not require any JS library:

http://rostislav-matl.blogspot.com/2011/06/moving-to-selenium-2-on-webdriver-part.html
Reply all
Reply to author
Forward
0 new messages