How do you dynamically add and remove classes from an element in jQuery?

Instruction: Demonstrate with code how to add and then remove a class from a selected element.

Context: Manipulating an element's class attribute is a fundamental jQuery skill, allowing for dynamic changes to styling and functionality.

Official answer available

Preview the opening of the answer, then unlock the full walkthrough.

Clarification & Assumption: The question assumes familiarity with jQuery, a popular JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. The ability to manipulate an element's class enables us to dynamically change its styling and behavior based on user interaction or other conditions.

Direct Answer with Explanation: To add a class to an element in jQuery, we use the .addClass() method. For instance, if we want to add a class named "active" to an element with the ID "menu", the code would look like this:...

Related Questions