Popular Searches
Popular Course Categories
Popular Courses

Click()

Working with Web Elements

Click() in Selenium WebDriver

The click() method in Selenium WebDriver is used to perform a click action on a web element. It is one of the most commonly used WebElement interaction methods in Selenium automation. Testers use click() to interact with buttons, links, checkboxes, radio buttons, menus, search buttons, submit buttons, navigation elements, and other clickable elements.

In a Selenium automation script, the usual process is to first locate a web element using a locator such as ID, Name, Class Name, XPath, CSS Selector, Link Text, or Partial Link Text and then call the click() method on the located element.

JustAcademy's Selenium Automation Testing course covers Selenium WebDriver, locators, web elements, browser automation, forms, buttons, waits, TestNG, Page Object Model, and practical automation projects. Explore Selenium Training at JustAcademy.

You can also visit JustAcademy Course Demo Registration to explore the course demo.


1. What is click() in Selenium?

The click() method is a Selenium WebElement method used to simulate a normal click interaction on a web element.

For example, if a webpage contains a Login button, Selenium can locate the Login button and perform a click operation.

driver.findElement(By.id("login")).click();

In this statement:

  • driver represents the WebDriver instance.
  • findElement() locates the required web element.
  • By.id("login") identifies the element using its ID.
  • click() performs the click action.


2. Basic Syntax of click()

element.click();

Another commonly used form is:

driver.findElement(By.id("button")).click();

The first approach is useful when the element is already stored in a WebElement variable, while the second approach directly locates and clicks the element.


3. How click() Works

The basic Selenium click workflow is:

Start

  ↓

Launch Browser

  ↓

Open Web Application

  ↓

Locate Web Element

  ↓

Verify Element

  ↓

Perform click()

  ↓

Application Processes Click

  ↓

Expected Action Occurs

  ↓

Verify Result

  ↓

Continue Test

For example, a login workflow can be represented as:

Enter Username

      ↓

Enter Password

      ↓

Locate Login Button

      ↓

Click Login Button

      ↓

Application Validates Credentials

      ↓

Dashboard Opens

      ↓

Verify Dashboard


4. Simple click() Example

Suppose the HTML page contains:

<button id="login">Login</button>

Selenium code:

driver.findElement(By.id("login")).click();

Selenium locates the button using the ID login and performs the click action.


5. Click Using ID

If an element has a unique ID, the ID locator can be used to locate the element.

driver.findElement(By.id("submit")).click();

HTML:

<button id="submit">Submit</button>

ID-based locators are generally simple and readable when the application provides stable unique IDs.


6. Click Using Name

The name attribute can also be used to locate a clickable element.

driver.findElement(By.name("login")).click();

HTML:

<button name="login">Login</button>


7. Click Using Class Name

The class name locator can be used when a suitable class identifies the element.

driver.findElement(By.className("login-button")).click();

HTML:

<button class="login-button">Login</button>

If an element contains multiple classes, By.className() should receive one individual class name rather than a complete space-separated class attribute.


8. Click Using XPath

XPath is frequently used when an element does not have a convenient unique ID or when a more flexible locator is required.

driver.findElement(By.xpath("//button[@id='login']")).click();

Clicking an element using its visible text:

driver.findElement(By.xpath("//button[text()='Login']")).click();

Using contains():

driver.findElement(By.xpath("//button[contains(text(),'Login')]")).click();

Using normalize-space():

driver.findElement(By.xpath("//button[normalize-space()='Login']")).click();


9. Click Using CSS Selector

CSS selectors can also be used to locate clickable elements.

driver.findElement(By.cssSelector("#login")).click();

Using a class:

driver.findElement(By.cssSelector(".login-button")).click();

Using an attribute:

driver.findElement(By.cssSelector("button[type='submit']")).click();


10. Click Using Link Text

Selenium provides By.linkText() for locating links using their complete visible text.

driver.findElement(By.linkText("Login")).click();

HTML:

<a href="/login">Login</a>


11. Click Using Partial Link Text

By.partialLinkText() can be used when only part of the link text is known.

driver.findElement(By.partialLinkText("Login")).click();

HTML:

<a href="/login">Login to Account</a>


12. Click a Button

Buttons are among the most common elements used with click().

driver.findElement(By.id("submitButton")).click();

Common button operations include:

  • Login
  • Submit
  • Search
  • Save
  • Continue
  • Register
  • Checkout
  • Confirm
  • Delete


13. Click a Link

A link can be clicked after locating it using different locator strategies.

driver.findElement(By.linkText("Home")).click();

XPath:

driver.findElement(By.xpath("//a[text()='Home']")).click();

CSS:

driver.findElement(By.cssSelector("a[href='/home']")).click();


14. Click a Checkbox

The click() method can be used to select or deselect a checkbox.

driver.findElement(By.id("terms")).click();

HTML:

<input type="checkbox" id="terms">

<label for="terms">I agree to the terms</label>

To select the checkbox only when it is not already selected:

WebElement checkbox = driver.findElement(By.id("terms"));

if (!checkbox.isSelected()) {

    checkbox.click();

}


15. Click a Radio Button

Radio buttons can also be selected using click().

WebElement maleRadio = driver.findElement(By.id("male"));

if (!maleRadio.isSelected()) {

    maleRadio.click();

}

HTML:

<input type="radio" id="male" name="gender">

<label for="male">Male</label>


16. Click Using WebElement

The element can be stored in a WebElement variable before clicking it.

WebElement loginButton = driver.findElement(By.id("login"));

loginButton.click();

This approach can improve readability and can be useful when the same element is referenced multiple times.


17. Direct Click vs WebElement Click

ApproachExampleUsage
Direct Clickdriver.findElement(By.id("login")).click();Simple one-time interaction
WebElement ClickWebElement button = driver.findElement(By.id("login")); button.click();Useful when storing or reusing the element


18. Click with Explicit Wait

Modern web applications often load elements dynamically. A button may be present in the DOM but may not yet be ready for interaction. An explicit wait can be used to wait for the element to become clickable.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(By.id("login"))

);

loginButton.click();

The elementToBeClickable() expected condition is commonly used when the test needs to wait for an element to become suitable for clicking.


19. Why Waits Are Important Before click()

A click may fail if the page is still loading, an element is covered by another element, or the application has not reached the required state.

Without synchronization:

driver.findElement(By.id("login")).click();

With explicit synchronization:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(By.id("login"))

);

loginButton.click();

Using an appropriate wait condition can make tests more stable than relying on fixed delays.


20. Click After Checking Visibility

You can check whether an element is displayed before interacting with it.

WebElement button = driver.findElement(By.id("submit"));

if (button.isDisplayed()) {

    button.click();

}

However, an element being displayed does not necessarily mean that it is ready to receive a click. Application state and synchronization should also be considered.


21. Click After Checking Enabled State

Some buttons remain disabled until the user completes required fields.

WebElement button = driver.findElement(By.id("submit"));

if (button.isEnabled()) {

    button.click();

}

This can be useful when the application dynamically enables or disables a button.


22. Common Exceptions During click()

ExceptionPossible ReasonPossible Approach
NoSuchElementExceptionElement cannot be locatedVerify locator and page state
ElementNotInteractableExceptionElement is not currently interactableCheck visibility, state, and synchronization
ElementClickInterceptedExceptionAnother element is blocking the clickHandle overlays, popups, or synchronization
StaleElementReferenceExceptionElement reference is no longer validLocate the element again
TimeoutExceptionExpected condition was not metCheck locator, page state, and wait configuration


23. ElementClickInterceptedException

ElementClickInterceptedException can occur when Selenium tries to click an element but another element receives or blocks the intended interaction.

Possible causes include:

  • Cookie popup
  • Modal dialog
  • Loading overlay
  • Sticky header
  • Advertisement overlay
  • Another element positioned over the target

For example:

driver.findElement(By.id("submit")).click();

If another element is blocking the button, the click may fail. The correct solution is to identify the blocking condition and handle it appropriately.


24. Handling Click Interception with Wait

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement submitButton = wait.until(

    ExpectedConditions.elementToBeClickable(By.id("submit"))

);

submitButton.click();

If an overlay is responsible for the problem, the test may also need to wait for the overlay to disappear before clicking the target element.


25. ElementNotInteractableException

This exception may occur when Selenium has located an element but the element cannot currently be interacted with.

Possible causes include:

  • The element is hidden.
  • The element is disabled.
  • The element is not in the required application state.
  • The page is still loading.
  • A dynamic UI update is still in progress.


26. Click with Login Automation

A typical login automation flow can be implemented using click().

driver.findElement(By.id("username")).sendKeys("admin");

driver.findElement(By.id("password")).sendKeys("admin123");

driver.findElement(By.id("login")).click();

The workflow is:

  1. Locate username field.
  2. Enter username.
  3. Locate password field.
  4. Enter password.
  5. Locate Login button.
  6. Click Login.
  7. Verify the resulting page.


27. Click with Form Submission

A submit button can trigger form submission.

driver.findElement(By.id("submit")).click();

Example HTML:

<form>

    <input id="name" type="text">

    <button id="submit" type="submit">Submit</button>

</form>


28. Click with Search Functionality

A common automation scenario is entering a search term and clicking the Search button.

driver.findElement(By.id("search")).sendKeys("Selenium");

driver.findElement(By.id("searchButton")).click();

The expected flow is:

Enter Search Term

      ↓

Click Search

      ↓

Application Processes Request

      ↓

Search Results Displayed

      ↓

Verify Results


29. Click with Navigation

Navigation links can be clicked to move between pages.

driver.findElement(By.linkText("Products")).click();

After clicking the link, the test can verify the resulting page.

String title = driver.getTitle();

System.out.println(title);


30. Click with Dropdown Menu

For custom dropdowns, click() can be used to open the dropdown before selecting an option.

driver.findElement(By.id("countryDropdown")).click();

driver.findElement(By.xpath("//li[normalize-space()='India']")).click();

For a standard HTML select element, Selenium's Select class is generally used instead of treating it like a custom dropdown.


31. Click with Dynamic Elements

Modern applications may generate dynamic IDs, classes, or other attributes. In such cases, a stable locator strategy and synchronization are important.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement addToCart = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//button[contains(@class,'add-to-cart')]")

    )

);

addToCart.click();

Dynamic XPath techniques such as contains(), starts-with(), and stable attribute combinations can help locate elements when some attributes change.


32. Click Using normalize-space()

When text contains unnecessary or inconsistent whitespace, XPath's normalize-space() function can be useful.

driver.findElement(

    By.xpath("//button[normalize-space()='Login']")

).click();


33. Click Using Parent and Child Relationship

An element can sometimes be located through its relationship with a parent element.

driver.findElement(

    By.xpath("//div[@class='login-container']//button")

).click();

This approach can be useful when the button does not have a unique attribute but its parent container provides a stable identification point.


34. Click Using XPath Axes

XPath axes can be used to locate an element relative to another element.

driver.findElement(

    By.xpath("//label[normalize-space()='Login']/following::button[1]")

).click();

Such relationships can be useful when direct attributes are insufficient for creating a stable locator.


35. Click Using JavaScriptExecutor

Selenium's normal WebElement click() should generally be considered first for standard user interactions. In specific situations where the native interaction cannot be completed, JavaScript can be used as an alternative technique.

WebElement button = driver.findElement(By.id("submit"));

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].click();", button);

JavaScript click should not automatically replace native click(). Before using it, investigate issues such as incorrect locators, synchronization, overlays, frames, or application state.


36. Native Click vs JavaScript Click

FeatureWebElement click()JavaScript Click
Syntaxelement.click()executeScript()
InteractionWebDriver element interactionJavaScript execution
Normal UsageStandard web element interactionSpecific exceptional situations
BehaviorCloser to normal WebDriver interactionCan bypass some normal UI interaction behavior
DebuggingUseful for detecting actual interaction problemsMay hide some UI interaction issues


37. Click with Actions Class

The Selenium Actions class provides APIs for advanced mouse and keyboard interactions.

WebElement button = driver.findElement(By.id("submit"));

Actions actions = new Actions(driver);

actions.click(button).perform();

The Actions class can also be used for operations such as double-click, right-click, hover, drag and drop, and combined keyboard-mouse actions.


38. WebElement click() vs Actions click()

FeatureWebElement click()Actions click()
Syntaxelement.click()actions.click(element).perform()
PurposeNormal click interactionAdvanced user interaction
ClassWebElementActions
Typical UsageButtons, links, checkboxesComplex mouse interaction sequences


39. Double Click

A double-click is different from a normal click and can be performed using the Actions class.

WebElement element = driver.findElement(By.id("item"));

Actions actions = new Actions(driver);

actions.doubleClick(element).perform();


40. Right Click

A context click can be used when the application requires a right-click interaction.

WebElement element = driver.findElement(By.id("item"));

Actions actions = new Actions(driver);

actions.contextClick(element).perform();


41. Click After Scrolling

Sometimes a page layout or application behavior requires the target element to be brought into view before interaction.

WebElement button = driver.findElement(By.id("submit"));

((JavascriptExecutor) driver).executeScript(

    "arguments[0].scrollIntoView(true);", button

);

button.click();

Scrolling should not be added automatically for every click. First determine whether the actual problem is caused by synchronization, overlays, or another UI condition.


42. Click Inside an iframe

If the clickable element is inside an iframe, Selenium must first switch to that frame.

driver.switchTo().frame("paymentFrame");

driver.findElement(By.id("pay")).click();

driver.switchTo().defaultContent();

The basic flow is:

Main Page

   ↓

Switch to iframe

   ↓

Locate Element

   ↓

Click Element

   ↓

Return to Main Document


43. Click with Multiple Windows or Tabs

If clicking an element opens a new window or tab, Selenium may need to switch to the appropriate window before continuing.

String parentWindow = driver.getWindowHandle();

 

driver.findElement(By.id("openWindow")).click();

 

for (String window : driver.getWindowHandles()) {

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

        break;

    }

}


44. Click with Alert

Some buttons display JavaScript alerts after they are clicked.

driver.findElement(By.id("delete")).click();

 

Alert alert = driver.switchTo().alert();

alert.accept();

The sequence is:

Click Button

   ↓

Alert Appears

   ↓

Switch to Alert

   ↓

Accept or Dismiss

   ↓

Continue Test


45. Click with Modal Popup

HTML-based modal dialogs can be handled by locating their buttons after the modal appears.

driver.findElement(By.id("delete")).click();

 

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement confirmButton = wait.until(

    ExpectedConditions.elementToBeClickable(By.id("confirmDelete"))

);

confirmButton.click();


46. Click in Page Object Model

In the Page Object Model, page elements and their actions can be maintained inside page classes.

public class LoginPage {

    private WebDriver driver;

 

    private By username = By.id("username");

    private By password = By.id("password");

    private By loginButton = By.id("login");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String value) {

        driver.findElement(username).sendKeys(value);

    }

 

    public void enterPassword(String value) {

        driver.findElement(password).sendKeys(value);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton).click();

    }

}

Test class:

LoginPage loginPage = new LoginPage(driver);

loginPage.enterUsername("admin");

loginPage.enterPassword("admin123");

loginPage.clickLogin();


47. Click with PageFactory

PageFactory can be used to declare WebElements using annotations.

public class LoginPage {

    WebDriver driver;

 

    @FindBy(id = "login")

    WebElement loginButton;

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

        PageFactory.initElements(driver, this);

    }

 

    public void clickLogin() {

        loginButton.click();

    }

}


48. Click with TestNG

Click operations are frequently used inside TestNG test methods.

@Test

public void loginTest() {

    driver.findElement(By.id("username")).sendKeys("admin");

    driver.findElement(By.id("password")).sendKeys("admin123");

    driver.findElement(By.id("login")).click();

}


49. Click and Assertions

After performing a click, the test should generally verify the expected application behavior.

driver.findElement(By.id("login")).click();

 

String title = driver.getTitle();

 

Assert.assertTrue(title.contains("Dashboard"));

The click performs the interaction, while the assertion verifies the expected result.


50. Click in E-Commerce Automation

Click operations are commonly used in end-to-end e-commerce automation.

driver.findElement(By.id("search")).sendKeys("Laptop");

driver.findElement(By.id("searchButton")).click();

driver.findElement(By.xpath("//button[contains(text(),'Add to Cart')]")).click();

driver.findElement(By.id("cart")).click();

driver.findElement(By.id("checkout")).click();

Flow:

Search Product

     ↓

Click Search

     ↓

View Search Results

     ↓

Click Add to Cart

     ↓

Open Cart

     ↓

Click Checkout


51. Click in Registration Testing

A registration test can contain several click operations.

driver.findElement(By.id("firstName")).sendKeys("John");

driver.findElement(By.id("lastName")).sendKeys("Smith");

driver.findElement(By.id("email")).sendKeys("[email protected]");

driver.findElement(By.id("terms")).click();

driver.findElement(By.id("register")).click();


52. Click in Logout Testing

Logout functionality can also be automated using click().

driver.findElement(By.id("profile")).click();

driver.findElement(By.id("logout")).click();

The test should then verify that the application has returned to the expected logged-out state.


53. Click in a Real-Time Automation Workflow

In real-world Selenium projects, click() is normally combined with locators, waits, assertions, page objects, and test frameworks.

Open Application

      ↓

Locate Username

      ↓

Enter Username

      ↓

Locate Password

      ↓

Enter Password

      ↓

Wait for Login Button

      ↓

Click Login

      ↓

Wait for Dashboard

      ↓

Verify Dashboard

      ↓

Continue Test


54. Common Mistakes While Using click()

  • Using an incorrect locator.
  • Using an unstable XPath.
  • Clicking before the element is ready.
  • Ignoring overlays and popups.
  • Using fixed delays everywhere.
  • Ignoring iframe context.
  • Ignoring multiple windows or tabs.
  • Using JavaScript click without investigating the native click failure.
  • Not checking whether a checkbox is already selected.
  • Not validating the expected result after clicking.


55. Best Practices for click()

  • Use stable locators.
  • Prefer native WebElement click() for normal interactions.
  • Use explicit waits for dynamically loaded elements.
  • Handle overlays and popups properly.
  • Verify the application's state before clicking.
  • Use Page Object Model for maintainable frameworks.
  • Avoid unnecessary Thread.sleep() calls.
  • Use Actions for advanced mouse interactions.
  • Use JavaScript click only for specific situations.
  • Validate the result after important click operations.


56. Practical Selenium click() Example

The following example demonstrates a login workflow using WebDriver, WebElement, explicit wait, and click().

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class ClickExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

 

        driver.manage().window().maximize();

        driver.get("https://example.com");

 

        driver.findElement(By.id("username"))

              .sendKeys("admin");

 

        driver.findElement(By.id("password"))

              .sendKeys("admin123");

 

        WebDriverWait wait = new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

        WebElement loginButton = wait.until(

            ExpectedConditions.elementToBeClickable(

                By.id("login")

            )

        );

 

        loginButton.click();

 

        driver.quit();

    }

}


57. click() Quick Reference

TaskExample
Click by IDdriver.findElement(By.id("login")).click();
Click by Namedriver.findElement(By.name("login")).click();
Click by Classdriver.findElement(By.className("button")).click();
Click by XPathdriver.findElement(By.xpath("//button[@id='login']")).click();
Click by CSSdriver.findElement(By.cssSelector("#login")).click();
Click by Link Textdriver.findElement(By.linkText("Login")).click();
Click by Partial Link Textdriver.findElement(By.partialLinkText("Log")).click();
Actions Clicknew Actions(driver).click(element).perform();
Double Clicknew Actions(driver).doubleClick(element).perform();
Right Clicknew Actions(driver).contextClick(element).perform();


58. Click() Interview Questions

Q1. What is click() in Selenium?

The click() method is a WebElement method used to perform a click interaction on a web element.

Q2. How do you click a button in Selenium?

driver.findElement(By.id("submit")).click();

Q3. Can click() be used on a checkbox?

Yes. click() can be used to select or deselect a checkbox. The selected state can be checked using isSelected().

Q4. Can click() be used on a link?

Yes. After locating the link as a WebElement, click() can be used to activate it.

Q5. What is ElementClickInterceptedException?

It can occur when another element blocks or intercepts the intended click interaction.

Q6. How can you wait for a button before clicking?

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement button = wait.until(

    ExpectedConditions.elementToBeClickable(By.id("submit"))

);

button.click();

Q7. What is the difference between click() and sendKeys()?

click() performs a click interaction, while sendKeys() is commonly used to enter keyboard input into an element.

Q8. What is the difference between click() and Actions.click()?

WebElement click() performs a standard element interaction, while Actions.click() belongs to Selenium's advanced user interaction API.

Q9. When can JavaScript click be used?

It can be considered for specific cases where the normal WebDriver interaction cannot be completed after investigating the underlying UI or synchronization issue.

Q10. Why should we validate after click()?

A successful click interaction does not by itself prove that the expected application behavior occurred. Assertions or other validations can verify the resulting state.


59. Click() Learning Checklist

  • Understand the click() method.
  • Understand WebElement interaction.
  • Practice clicking buttons.
  • Practice clicking links.
  • Practice checkbox interaction.
  • Practice radio button interaction.
  • Practice XPath-based clicking.
  • Practice CSS-based clicking.
  • Understand explicit waits.
  • Handle click interception.
  • Handle dynamic elements.
  • Understand iframe handling.
  • Understand multiple window handling.
  • Practice Actions class.
  • Understand JavaScript click.
  • Use Page Object Model.
  • Use assertions after important interactions.


60. Conclusion

The click() method is a fundamental Selenium WebDriver operation for interacting with buttons, links, checkboxes, radio buttons, menus, forms, and other clickable elements. Reliable click automation requires more than simply calling click(); testers should also use stable locators, appropriate synchronization, correct frame or window context, proper handling of overlays and dynamic elements, and validation of the expected result.

For structured Selenium learning covering WebDriver, locators, web elements, waits, TestNG, Page Object Model, frameworks, and practical automation projects, visit JustAcademy Selenium Training.

For the course demo, visit JustAcademy Course Demo Registration.

whatsapp