Bird
0
0

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?

hard📝 Application Q15 of 15
Selenium Java - JavaScriptExecutor
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
}
AUse <code>checkbox.setAttribute("checked", "true")</code>
BUse JavaScriptExecutor: <code>js.executeScript("arguments[0].setAttribute('checked', 'true')", checkbox);</code>
CUse <code>checkbox.click()</code> to check the box
DUse <code>checkbox.getAttribute("checked") = "true"</code>
Step-by-Step Solution
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]
Quick Trick: Check attribute with getAttribute; set with JSExecutor [OK]
Common Mistakes:
MISTAKES
  • Trying to call setAttribute directly on WebElement
  • Using assignment on getAttribute() result
  • Using click() which toggles but does not set attribute directly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes