Modify an element's attribute using JavaScript in Selenium
Preconditions (2)
✅ Expected Result: The input element with id 'username-input' has its placeholder attribute changed to 'Enter your username'
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Initialize the WebDriver (example with Chrome) driver = webdriver.Chrome() try: # Open the target web page driver.get('https://example.com') # Wait until the element with id 'username-input' is present wait = WebDriverWait(driver, 10) element = wait.until(EC.presence_of_element_located((By.ID, 'username-input'))) # Use JavaScript to modify the placeholder attribute driver.execute_script("arguments[0].setAttribute('placeholder', 'Enter your username')", element) # Verify the placeholder attribute is updated updated_placeholder = element.get_attribute('placeholder') assert updated_placeholder == 'Enter your username', f"Expected placeholder to be 'Enter your username' but got '{updated_placeholder}'" finally: driver.quit()
This script starts by opening the browser and navigating to the target page.
It waits explicitly for the element with id 'username-input' to be present to avoid errors.
Then it uses Selenium's execute_script method to run JavaScript that changes the element's placeholder attribute.
Finally, it retrieves the updated attribute and asserts it matches the expected value.
The finally block ensures the browser closes even if the test fails.
Now add data-driven testing to modify the placeholder attribute with three different values: 'Enter username', 'Type your user ID', and 'User login here'.
driver.execute_script("arguments[0].setAttribute('disabled', 'true')", element)setAttribute to add or change the 'disabled' attribute of the element to 'true'.arguments[0] refers to the first argument passed after the script string, which is the element.setAttribute('attributeName', 'value'). driver.execute_script("arguments[0].setAttribute('class', 'active')", element) uses this correctly with arguments[0].element = driver.find_element(By.ID, 'submit-btn')
driver.execute_script("arguments[0].setAttribute('data-test', 'passed')", element)
attr_value = element.get_attribute('data-test')
print(attr_value)get_attribute('data-test') fetches the updated value, which is 'passed'.element = driver.find_element(By.CSS_SELECTOR, '.btn')
driver.execute_script("arguments[0].setAttribute('title', title)", element)arguments[1] or similar.Pass the test and this pattern moves unknown