Bird
0
0

You wrote this code to click a button via JavaScript but it throws a ClassCastException:

medium📝 Debug Q14 of 15
Selenium Java - JavaScriptExecutor
You wrote this code to click a button via JavaScript but it throws a ClassCastException:
JavascriptExecutor js = driver;
js.executeScript("arguments[0].click();", button);

What is the error and how to fix it?
AexecuteScript method does not exist in JavascriptExecutor
BUse driver.executeScript directly without casting
Cbutton element is null, causing exception
Ddriver must be cast to JavascriptExecutor before assignment
Step-by-Step Solution
Solution:
  1. Step 1: Identify cause of ClassCastException

    Assigning driver directly to JavascriptExecutor without cast causes ClassCastException.
  2. Step 2: Correct casting syntax

    Cast driver to (JavascriptExecutor) before assignment: JavascriptExecutor js = (JavascriptExecutor) driver;
  3. Final Answer:

    driver must be cast to JavascriptExecutor before assignment -> Option D
  4. Quick Check:

    Cast driver to JavascriptExecutor to avoid ClassCastException [OK]
Quick Trick: Always cast driver to JavascriptExecutor before use [OK]
Common Mistakes:
MISTAKES
  • Ignoring casting and assigning directly
  • Blaming executeScript method existence
  • Assuming button element causes ClassCastException

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes