How to use JavaScript in Selenium to click an Element?

SeleniumAutomation TestingTesting Tools

We can use the JavaScript Executor in Selenium to click an element.

Selenium can execute JavaScript commands with the help of the method executeScript.

Sometimes while clicking a link, we get the IllegalStateException, to avoid this exception, the JavaScript executor is used instead of the method click. The parameters to be passed to the executeScript method to click an element are - arguments[0].click(); and the web element locator.

Syntax

WebElement m=driver.findElement(By.linkText("Company"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", m);

Let us click the link Company on the below page −

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ClickLnkJS{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement m = driver.findElement(By.linkText("Company"));
      // click with Javascript Executor
      JavascriptExecutor js = (JavascriptExecutor) driver;
      js.executeScript("arguments[0].click();", m);
      System.out.println("Page navigated to:" + driver.getTitle());
      driver.quit();
   }
}

Output

raja
Published on 03-Apr-2021 10:10:50
Advertisements