Use the click() method on a WebElement to simulate a mouse click.
Basic click:
Java
driver.findElement(By.id("loginBtn")).click();
driver.findElement(By.cssSelector(".btn-submit")).click();
driver.findElement(By.xpath("//button[text()=''Login'']")).click();
Best practice — wait before clicking:
Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement btn = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn")));
btn.click();
Click with JavaScript (for hidden or overlapping elements):
Java
WebElement btn = driver.findElement(By.id("loginBtn"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", btn);
Common click errors:
| Error | Cause | Fix |
|---|---|---|
ElementNotInteractableException | Element is hidden | JS click or scroll into view |
ElementClickInterceptedException | Another element overlaps | Wait for overlay to disappear |
StaleElementReferenceException | DOM changed after find | Re-find the element |
TimeoutException | Element not found in time | Increase wait timeout |
