Bird
0
0

You want to set the attribute placeholder of an input element to "Enter name" using Selenium Java. Which code snippet fixes the error below?

medium📝 Debug Q14 of 15
Selenium Java - JavaScriptExecutor
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
AUse <code>input.sendKeys("Enter name")</code>
BReplace with <code>input.getAttribute("placeholder") = "Enter name";</code>
CUse JavaScriptExecutor: <code>js.executeScript("arguments[0].setAttribute('placeholder', 'Enter name')", input);</code>
DUse <code>input.setValue("Enter name")</code>
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes