Bird
Raised Fist0
Selenium Javatesting~10 mins

Getting and setting attributes in Selenium Java - Test Execution Trace

Choose your learning style10 modes available
Test Overview

This test opens a web page, finds an input field, gets its current placeholder attribute, sets a new placeholder attribute using JavaScript, and verifies the change.

Test Code - JUnit with Selenium WebDriver
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class AttributeTest {
    WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    public void testGetAndSetAttribute() {
        driver.get("https://example.com/form");
        WebElement inputField = driver.findElement(By.id("username"));

        // Get the placeholder attribute
        String originalPlaceholder = inputField.getAttribute("placeholder");

        // Set a new placeholder attribute using JavaScript
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].setAttribute('placeholder', 'Enter your user ID')", inputField);

        // Get the updated placeholder attribute
        String updatedPlaceholder = inputField.getAttribute("placeholder");

        // Verify the placeholder changed
        assertEquals("Enter your user ID", updatedPlaceholder);
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready—PASS
2Navigates to https://example.com/formPage with form and input field with id 'username' is loaded—PASS
3Finds input element by id 'username'Input field element located on the page—PASS
4Gets the 'placeholder' attribute of the input fieldOriginal placeholder attribute value retrieved (e.g., 'Enter username')placeholder attribute is not nullPASS
5Sets new 'placeholder' attribute to 'Enter your user ID' using JavaScriptInput field's placeholder attribute updated in the DOM—PASS
6Gets the updated 'placeholder' attribute of the input fieldUpdated placeholder attribute value retrievedplaceholder attribute equals 'Enter your user ID'PASS
7Assertion checks that placeholder attribute is updated correctlyTest verifies the attribute changeassertEquals("Enter your user ID", updatedPlaceholder)PASS
8Browser closes and test endsBrowser window closed—PASS
Failure Scenario
Failing Condition: Input element with id 'username' is not found on the page
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify after setting the new placeholder attribute?
AThat the input field is visible on the page
BThat the page URL is correct
CThat the placeholder attribute value is updated to 'Enter your user ID'
DThat the browser is Chrome
Key Result
Use JavaScript execution in Selenium to set attributes that cannot be changed directly via WebElement methods, and always verify attribute changes with assertions.

Practice

(1/5)
1. What is the primary method to get an attribute value of a web element in Selenium Java?
easy
A. Using driver.getAttribute("attributeName")
B. Using element.setAttribute("attributeName")
C. Using element.getText()
D. Using element.getAttribute("attributeName")

Solution

  1. Step 1: Understand the method to retrieve attribute

    In Selenium Java, getAttribute is used on a WebElement to fetch the value of an attribute.
  2. Step 2: Identify correct usage

    The syntax is element.getAttribute("attributeName"), which returns the attribute's value as a string.
  3. Final Answer:

    Using element.getAttribute("attributeName") -> Option D
  4. Quick Check:

    Get attribute = element.getAttribute("attributeName") [OK]
Hint: Remember: getAttribute reads, setAttribute does not exist directly [OK]
Common Mistakes:
  • Confusing getAttribute with setAttribute
  • Trying to use driver.getAttribute instead of element.getAttribute
  • Using getText() to get attribute values
2. Which of the following is the correct way to set an attribute value of a web element in Selenium Java?
easy
A. Using JavaScriptExecutor to run arguments[0].setAttribute('value', 'newValue')
B. element.setAttribute("value", "newValue")
C. element.getAttribute("value") = "newValue"
D. element.setValue("newValue")

Solution

  1. Step 1: Understand Selenium's limitation on setting attributes

    Selenium WebElement does not have a direct setAttribute method.
  2. Step 2: Use JavaScriptExecutor to set attribute

    We use JavaScriptExecutor to run JavaScript code that sets the attribute, e.g., arguments[0].setAttribute('value', 'newValue').
  3. Final Answer:

    Using JavaScriptExecutor to run arguments[0].setAttribute('value', 'newValue') -> Option A
  4. Quick Check:

    Set attribute = JavaScriptExecutor + setAttribute() [OK]
Hint: Set attributes via JavaScriptExecutor, not WebElement methods [OK]
Common Mistakes:
  • Trying to call setAttribute directly on WebElement
  • Assigning value to getAttribute() result
  • Using non-existent setValue() method
3. Consider the following Selenium Java code snippet:
WebElement input = driver.findElement(By.id("username"));
String value = input.getAttribute("value");
System.out.println(value);

If the input field has value="testUser", what will be printed?
medium
A. testUser
B. null
C. value
D. username

Solution

  1. Step 1: Identify the attribute being fetched

    The code calls getAttribute("value") on the input element, which returns the current value attribute.
  2. Step 2: Match attribute value with output

    The input field has value="testUser", so value variable will be "testUser" and printed.
  3. Final Answer:

    testUser -> Option A
  4. Quick Check:

    getAttribute("value") = "testUser" [OK]
Hint: getAttribute returns actual attribute value, not element text [OK]
Common Mistakes:
  • Confusing getAttribute("value") with getText()
  • Expecting attribute name instead of value
  • Assuming null if attribute exists
4. You want to set the attribute placeholder of an input element to "Enter name" using Selenium Java. Which code snippet fixes the error below?
// Current code
WebElement input = driver.findElement(By.id("name"));
input.setAttribute("placeholder", "Enter name"); // Error: cannot find symbol
medium
A. Use input.sendKeys("Enter name")
B. Replace with input.getAttribute("placeholder") = "Enter name";
C. Use JavaScriptExecutor: js.executeScript("arguments[0].setAttribute('placeholder', 'Enter name')", input);
D. Use input.setValue("Enter name")

Solution

  1. Step 1: Identify why error occurs

    WebElement does not have a setAttribute method, so calling it causes a compile error.
  2. Step 2: Use JavaScriptExecutor to set attribute

    JavaScriptExecutor can run JavaScript to set attributes on elements, e.g., arguments[0].setAttribute('placeholder', 'Enter name').
  3. Final Answer:

    Use JavaScriptExecutor: js.executeScript("arguments[0].setAttribute('placeholder', 'Enter name')", input); -> Option C
  4. Quick Check:

    Set attribute via JSExecutor = Use JavaScriptExecutor: js.executeScript("arguments[0].setAttribute('placeholder', 'Enter name')", input); [OK]
Hint: Set attributes only via JavaScriptExecutor, not WebElement methods [OK]
Common Mistakes:
  • Trying to assign value to getAttribute()
  • Using non-existent setValue() method
  • Using sendKeys() which inputs text, not sets attribute
5. You want to verify if a checkbox is checked by reading its checked attribute using Selenium Java. Which approach correctly checks this and sets it checked if not already?
WebElement checkbox = driver.findElement(By.id("agree"));
String checked = checkbox.getAttribute("checked");
if (checked == null) {
    // Set checked attribute here
}
hard
A. Use checkbox.setAttribute("checked", "true")
B. Use JavaScriptExecutor: js.executeScript("arguments[0].setAttribute('checked', 'true')", checkbox);
C. Use checkbox.click() to check the box
D. Use checkbox.getAttribute("checked") = "true"

Solution

  1. Step 1: Check if checkbox is checked by reading 'checked' attribute

    If getAttribute("checked") returns null, checkbox is not checked.
  2. Step 2: Set 'checked' attribute using JavaScriptExecutor

    Since WebElement has no setAttribute, use JavaScriptExecutor to set checked attribute to "true".
  3. Final Answer:

    Use JavaScriptExecutor: js.executeScript("arguments[0].setAttribute('checked', 'true')", checkbox); -> Option B
  4. Quick Check:

    Set attribute via JSExecutor = Use JavaScriptExecutor: js.executeScript("arguments[0].setAttribute('checked', 'true')", checkbox); [OK]
Hint: Check attribute with getAttribute; set with JSExecutor [OK]
Common Mistakes:
  • Trying to call setAttribute directly on WebElement
  • Using assignment on getAttribute() result
  • Using click() which toggles but does not set attribute directly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard