WebDriver click() vs JavaScript click().


We can click a link with the webdriver click and Javascript click. For the Selenium webdriver click of a link we can use link text and partial link text locator. We can use the methods driver.findElement(By.linkText()) and driver.findElement(By.partialLinkText()) to click.

The links in an html code are enclosed in an anchor tag. The link text enclosed within the anchor tag is passed as argument to the driver.findElement(By.linkText(<link text>)) method. The partial matching link text enclosed within the anchor tag is passed as argument to the driver.findElement(By.partialLinkText(<partial link text>)) method. Finally to click on the link the click method is used.

Let us see the html code of a link having the anchor tag.

Example

Code Implementation.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class DriverClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify link with link text locator
      driver.findElement(By.linkText("Write for us")).click();
      System.out.println("Page title after click: " + driver.getTitle());
   }
}

We can also perform web operations like clicking on a link with Javascript Executor in Selenium. We shall use the executeScript method and pass argument index.click() and webelement to be clicked as arguments to the method.

Example

Code Implementation with Javascript executor.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.By;
public class DriverClickJs{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify link
      WebElement l = driver.findElement(By.linkText("Write for us"));
      //click link with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript("arguments[0].click();", l);
      System.out.println("Page title after click: " + driver.getTitle());
   }
}

Output

Updated on: 26-Oct-2020

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements