Setting Element Values

Introduction

Normally, Selenium enters text into input fields using the send_keys() method. However, some modern web applications use custom JavaScript frameworks that prevent send_keys() from working as expected.

In these situations, JavaScript Executor can directly set the value of an input element by modifying its DOM property. If the application listens for user input events, Selenium can also trigger an input event to ensure the application recognizes the change.

In this tutorial, you’ll learn how to set element values using JavaScript Executor in Selenium with Python, along with practical examples, real-world scenarios, common mistakes, and best practices.


Why Use JavaScript to Set Values?

Most of the time, this works perfectly:

element.send_keys("12345")

However, some applications:

  • Use custom JavaScript controls.

  • Ignore send_keys().

  • Require JavaScript events to update the UI.

In these cases, JavaScript Executor can set the value directly.


How JavaScript Sets Values

JavaScript modifies the input element like this:

element.value = "12345";

If the application listens for user input, an input event should also be dispatched.


Example

from selenium import webdriver
from selenium.webdriver.common.by import By


# Topic: 32. JavaScript Executor - Setting Element Values
# Practice site: https://the-internet.herokuapp.com/inputs
# Run: pytest -s 32_examples/test_03_setting_element_values.py
#
# JavaScript can set an element value directly. Dispatch an input event when the
# application listens for user input events.


def test_set_input_value_with_javascript:
    driver = webdriver.Chrome()

    try:
        driver.get("https://the-internet.herokuapp.com/inputs")

        number_input = driver.find_element(By.TAG_NAME, "input")
        driver.execute_script(
            """
            arguments[0].value = '12345';
            arguments[0].dispatchEvent(new Event('input', { bubbles: true }));
            """,
            number_input,
        )

        assert number_input.get_attribute("value") == "12345"
    finally:
        driver.quit()

Understanding the Code

Import Required Libraries

from selenium import webdriver
from selenium.webdriver.common.by import By

These modules are required to launch the browser and locate web elements.


Create a Chrome Browser Instance

driver = webdriver.Chrome()

Starts a new Chrome browser session.


Open the Practice Website

driver.get("https://the-internet.herokuapp.com/inputs")

Navigates to the Inputs practice page.


Locate the Input Field

number_input = driver.find_element(
    By.TAG_NAME,
    "input"
)

Locates the input field where the value will be updated.


Set the Value Using JavaScript

driver.execute_script(
    """
    arguments[0].value = '12345';
    arguments[0].dispatchEvent(
        new Event('input', { bubbles: true })
    );
    """,
    number_input,
)

This JavaScript performs two actions:

  • Sets the input field’s value to 12345.

  • Dispatches an input event so that JavaScript frameworks (such as React, Angular, or Vue) recognize the value change.

Here, arguments[0] refers to the number_input element passed from Python.


Verify the Updated Value

assert number_input.get_attribute(
    "value"
) == "12345"

Retrieves the value from the input field and verifies that it matches the expected value.

If the value is different, the test fails.


Close the Browser

driver.quit()

Closes the browser and ends the WebDriver session.


Practical Example

Suppose an online banking application uses a custom numeric input that blocks normal keyboard typing.

The automation script:

  • Opens the payment form.

  • Uses JavaScript to set the account number.

  • Dispatches the required input event.

  • Verifies that the value is accepted.


Automation Testing Example

Consider an enterprise web application built with React.

Changing an input value requires both:

  • Updating the input’s value.

  • Triggering an input event.

The automation script uses JavaScript Executor to perform both actions so the application updates correctly.


Real-World Example

Setting element values with JavaScript is commonly used in:

  • Banking applications

  • Enterprise dashboards

  • React applications

  • Angular applications

  • Vue.js applications

  • Custom JavaScript controls

  • Single Page Applications (SPA)

Examples include numeric fields, hidden inputs, custom widgets, and framework-controlled form elements.


Advantages of Using JavaScript to Set Values

  • Works with custom JavaScript controls.

  • Bypasses typing restrictions.

  • Supports modern JavaScript frameworks.

  • Updates DOM properties directly.

  • Can trigger application events when needed.


Common Mistakes Beginners Make

Using JavaScript Instead of send_keys() Everywhere

Whenever possible, use Selenium’s send_keys() because it better simulates real user behavior.

Use JavaScript only when necessary.


Forgetting to Dispatch the Input Event

Some applications update their internal state only after receiving an input event.

Without dispatching the event, the displayed value may change but the application may not recognize it.


Modifying the DOM Without Verification

Always verify that the expected value has actually been applied after executing JavaScript.


Assuming All Applications Behave the Same

Different frameworks handle input changes differently.

Always understand how the target application processes user input.


Best Practices

  • Prefer send_keys() whenever possible.

  • Use JavaScript only when standard input methods fail.

  • Dispatch the appropriate events when required.

  • Verify the updated value after execution.

  • Keep JavaScript snippets short and easy to understand.


Conclusion

JavaScript Executor allows Selenium to set input values directly in the DOM, making it useful for applications where normal typing is restricted or controlled by JavaScript frameworks. By updating the value and dispatching the appropriate events, Selenium can successfully automate many modern web applications that rely on dynamic input handling.


Frequently Asked Questions (FAQs)

Why use JavaScript instead of send_keys()?

Use JavaScript only when send_keys() cannot interact correctly with the application or when framework-specific behavior requires direct DOM manipulation.


Why is the input event dispatched?

Many modern JavaScript frameworks listen for input events to detect changes and update the application’s internal state.


What does arguments[0] represent?

arguments[0] refers to the first Python object passed into the JavaScript code—in this example, the input element.


Can JavaScript update any input field?

Yes, provided the application allows the value to be modified through JavaScript.


Where is this technique commonly used?

It is commonly used in React, Angular, Vue.js, Single Page Applications, enterprise dashboards, banking systems, and custom JavaScript controls.


Key Takeaways

  • send_keys() should be the first choice for entering text.

  • JavaScript Executor can directly modify input values.

  • Dispatch an input event when the application depends on it.

  • Verify the updated value after execution.

  • Use JavaScript only when it aligns with the application’s behavior.

  • This technique is especially useful for modern JavaScript-based web applications.