0
0
Selenium Pythontesting~5 mins

Modifying element attributes with JS in Selenium Python

Choose your learning style9 modes available
Introduction

Sometimes, you need to change a web page element's attribute to test how the page behaves. Using JavaScript lets you do this easily during tests.

When you want to change a button's disabled state to enabled for testing.
When you need to update an input field's placeholder text dynamically.
When you want to add or remove a CSS class to check style changes.
When you want to simulate a change in an element's attribute that normally requires user action.
When you want to test how the page reacts to attribute changes without reloading.
Syntax
Selenium Python
driver.execute_script("arguments[0].setAttribute('attributeName', 'newValue')", element)
Use execute_script to run JavaScript code in the browser from Selenium.
arguments[0] refers to the web element passed from Selenium to JavaScript.
Examples
This disables a button by setting its 'disabled' attribute to 'true'.
Selenium Python
driver.execute_script("arguments[0].setAttribute('disabled', 'true')", button_element)
This changes the placeholder text of an input field.
Selenium Python
driver.execute_script("arguments[0].setAttribute('placeholder', 'Enter your name')", input_element)
This sets the CSS class of a div to 'highlighted' to change its style.
Selenium Python
driver.execute_script("arguments[0].setAttribute('class', 'highlighted')", div_element)
Sample Program

This script opens a page with a button, prints its disabled attribute (should be None), then disables it using JavaScript and prints the attribute again (should be 'true').

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Setup WebDriver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

try:
    # Open a simple test page
    driver.get('data:text/html,<button id="btn1">Click me</button>')

    # Find the button element
    button = driver.find_element(By.ID, 'btn1')

    # Initially, button is enabled
    print('Initially disabled attribute:', button.get_attribute('disabled'))

    # Disable the button using JS
    driver.execute_script("arguments[0].setAttribute('disabled', 'true')", button)

    # Check if disabled attribute is set
    print('After JS modification disabled attribute:', button.get_attribute('disabled'))

finally:
    time.sleep(1)  # Pause to see the browser if needed
    driver.quit()
OutputSuccess
Important Notes

Always pass the element as an argument to execute_script to avoid errors.

Modifying attributes with JS does not always trigger events; you may need to trigger them manually if needed.

Summary

You can change element attributes during tests using JavaScript with Selenium's execute_script.

This helps test different states without user interaction.

Remember to check the attribute after modification to confirm the change.