jQuery CSS Classes

The jQuery CSS class manipulation methods allow you to dynamically add, remove, or toggle classes for HTML elements. These methods include addClass(), removeClass(), and toggleClass(). They are useful for creating interactive and dynamic web applications.

Key Topics

Using addClass()

The addClass() method adds one or more classes to the selected elements.

$("#element").addClass("highlight");

Explanation: This code adds the class highlight to the element with the ID element.

Using removeClass()

The removeClass() method removes one or more classes from the selected elements.

$("#element").removeClass("highlight");

Explanation: This code removes the class highlight from the element with the ID element.

Using toggleClass()

The toggleClass() method toggles (adds or removes) a class for the selected elements based on their current state.

$("#element").toggleClass("highlight");

Explanation: This code toggles the class highlight on the element with the ID element. If the class is present, it is removed; if not, it is added.

Example: Manipulating CSS Classes


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery CSS Classes Example</title>
    <style>
        .highlight {
            background-color: yellow;
            font-weight: bold;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <p id="text">This is a sample text.</p>
    <button id="addClassButton">Add Class</button>
    <button id="removeClassButton">Remove Class</button>
    <button id="toggleClassButton">Toggle Class</button>

    <script>
        $(document).ready(function() {
            $("#addClassButton").click(function() {
                $("#text").addClass("highlight");
            });
            $("#removeClassButton").click(function() {
                $("#text").removeClass("highlight");
            });
            $("#toggleClassButton").click(function() {
                $("#text").toggleClass("highlight");
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates adding, removing, and toggling the highlight class on a paragraph element using buttons.

Key Takeaways

  • Dynamic Styling: Use addClass(), removeClass(), and toggleClass() to dynamically update styles.
  • Interactive Design: These methods are ideal for creating interactive and responsive UI effects.
  • Efficiency: Apply multiple classes in a single call by passing a space-separated list of class names.