# 5.11. Click Element via JS

Selenium đã có sẵn hàm `click()` nhưng trong một số trường hợp trong quá trình làm test bạn sẽ cần tới cách này. Bản thân Selenium được xây dựng từ nền tảng JavaScripts nên đây cũng là một trong những cách mình có thể dùng nó nếu như những cách thông thường không làm được.

Đầu tiên ta cần khởi tạo 1 biến `executor`

```java
JavascriptExecutor executor = (JavascriptExecutor) driver;
```

Sử dụng đoạn code dưới đây để dùng JavaScript click vào một đối tượng

```java
executor.executeScript("arguments[0].click();", element);
```

Và để sau này có thể tái sử dụng lại ta có thể tạo cho nó một hàm:

```java
private void clickElement(WebElement element) {
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", element);
}
```

Và đây là cách dùng

```java
WebElement seeSearchResultsButton = driver.findElement(By.cssSelector(".btn-search"));
clickElement(seeSearchResultsButton);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tvn.gitbook.io/selenium-java/examples/click-element-via-js.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
