Click on Element using JavaScript executor in Selenium WebDriver

By: Slav Kurochkin

There is some situations where I would use JavaScript executor to click on specific element. And the main reason is to avoid dependency on dynamic data, cause in my experience this areas of the
tests mostly go throw "Falls Positive" errors, when tests is failed because of something went wrong during test execution and not because software got broken.
Here is an example how you can click on element using jQuery and JavaScript:

$("#element_id").click();

document.getElementById('element_id').click();

To test it, simply open Chrome Developer tool find your CSS locator:

And execute it via Console:

 $("#element_id").click();

Don't forget hit "Enter" button

So how would you use it in Selenium?

First you will need to create JavaScript Executor

 private static JavascriptExecutor js = (JavascriptExecutor)driver;

Then you would execute script:

 js.executeScript("document.getElementById('element_id').click();")

In some cases you would simply use CSS Selectors and contained Text, similar to XPATH.

I think the best practice would be abstract "clickOnElementWithCssSelector" method and provide CSS selector as argument
to that method.

First I would do, is declare a String on top of PageObject class, the reason why I would do it (is the same as why we using PageFactory), easy to find and maintain code

 String cssTextContain = "span:contains('Some Text In Here')";

And pass this string to our method

        
 clickOnElementWithCSS(cssTextContain);

Then abstracted method will do final JavaScript Execution

public static void clickOnElementWithCssSelector(String cssSelector){
        js.executeScript("$("" + cssSelector + "").click();");
    }
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.