OA. free
Free
Accenture Core Computer Science Core Computer Science Medium

You are working on a web application landing page.

Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.

You are working on a web application landing page. You have two CSS class names: red and green, and a button that toggles between them.

Which of the following JavaScript DOM methods correctly toggles between the two class states when the button is clicked?

Choose one option.
Show answer & explanation
Answer: A. element.classList.toggle('red'); element.classList.toggle('green');

Option A uses the classList.toggle() method, which adds a class if it's absent or removes it if present. Calling toggle on both 'red' and 'green' alternates between the two states on each button click. Option B assigns both classes simultaneously (not a toggle), Option C targets inline style color (not classes), and Option D removes all classes entirely.

Step-by-step Derivation:
Understanding classList.toggle():

  • toggle('red') → if 'red' is present, remove it; else add it
  • toggle('green') → if 'green' is present, remove it; else add it

Execution trace on repeated clicks:
Click 1: Element has neither class → adds 'red', removes 'green' → class='red'
Click 2: Element has 'red' → removes 'red', adds 'green' → class='green'
Click 3: Element has 'green' → adds 'red', removes 'green' → class='red'

This correctly alternates between the two classes. Other options fail because: B always sets both classes (no toggle), C modifies inline styles not classes, D removes all classes and breaks the cycle.