Lesson 17: jQuery Manipulating CSS
Master jQuery CSS manipulation techniques with interactive examples. Learn to dynamically change styles, classes, and properties on your web pages.
Understanding jQuery CSS Manipulation
jQuery provides powerful methods to manipulate CSS styles and classes, allowing you to dynamically change the appearance of elements based on user interactions or application state.
addClass()
- Adds one or more classes to selected elementsremoveClass()
- Removes one or more classes from selected elementstoggleClass()
- Toggles between adding/removing classescss()
- Gets or sets style propertieshasClass()
- Checks if any element has a specific class
Method | Description | Example |
---|---|---|
addClass() |
Adds one or more classes to elements | $("p").addClass("highlight") |
removeClass() |
Removes one or more classes from elements | $("p").removeClass("highlight") |
toggleClass() |
Toggles between adding/removing classes | $("p").toggleClass("highlight") |
css() |
Gets or sets CSS properties | $("p").css("color", "red") |
The addClass() Method
The addClass()
method adds one or more classes to the selected elements. This is the preferred way to change styles as it keeps your CSS separate from your JavaScript.
Example 17.1: Adding Classes
Add different classes to elements:
// addClass() examples $("#add-highlight").click(function() { $("#card1").addClass("highlight"); }); $("#add-success").click(function() { $("#card2").addClass("success"); }); $("#add-warning").click(function() { $("#card3").addClass("warning"); }); $("#add-error").click(function() { $("#card4").addClass("error"); }); $("#reset-classes").click(function() { $(".content-card").removeClass("highlight success warning error"); });
The removeClass() Method
The removeClass()
method removes one or more classes from selected elements. You can remove specific classes or all classes at once.
Example 17.2: Removing Classes
Remove classes from elements:
This box has multiple classes applied
// removeClass() examples $("#remove-border").click(function() { $("#box1").removeClass("border-primary rotate"); }); $("#remove-text").click(function() { $("#box1").removeClass("text-large text-italic text-underline"); }); $("#remove-all").click(function() { $("#box1").removeClass(); });
The toggleClass() Method
The toggleClass()
method toggles between adding and removing classes from selected elements. This is perfect for creating interactive elements that change state.
Example 17.3: Toggling Classes
Toggle different classes on elements:
// toggleClass() examples $("#toggle-highlight").click(function() { $("#toggle-card1").toggleClass("highlight"); }); $("#toggle-border").click(function() { $("#toggle-card2").toggleClass("border-primary"); }); $("#toggle-text").click(function() { $("#toggle-card1, #toggle-card2").toggleClass("text-large text-italic"); });
The css() Method
The css()
method sets or returns one or more style properties for the selected elements. It can be used for direct style manipulation when classes aren't sufficient.
Example 17.4: Setting CSS Properties
Manipulate CSS properties directly:
This box will reflect the CSS changes you make
// css() method examples $("#apply-css").click(function() { const bgColor = $("#bg-color").val(); const textColor = $("#text-color").val(); const fontSize = $("#font-size").val() + "px"; $("#css-box").css({ "background-color": bgColor, "color": textColor, "font-size": fontSize }); }); $("#font-size").on("input", function() { $("#font-size-value").text($(this).val() + "px"); }); $("#reset-css").click(function() { $("#css-box").css({ "background-color": "", "color": "", "font-size": "" }); $("#bg-color").val("#e3f2fd"); $("#text-color").val("#333333"); $("#font-size").val("16"); $("#font-size-value").text("16px"); });
The hasClass() Method
The hasClass()
method checks if any of the selected elements have a specific class. This is useful for conditional logic based on element state.
Example 17.5: Checking for Classes
Check if elements have specific classes:
// hasClass() examples $("#check-class").click(function() { const isActive = $("#state-card").hasClass("active"); const isHighlighted = $("#state-card").hasClass("highlight"); let result = "Element classes: "; result += isActive ? "active " : ""; result += isHighlighted ? "highlight" : ""; if (!isActive && !isHighlighted) { result = "Element has no classes applied"; } $("#class-result").text(result); }); $("#toggle-state").click(function() { $("#state-card").toggleClass("active"); }); $("#state-card").click(function() { $(this).toggleClass("highlight"); });
Practical Applications
jQuery CSS manipulation is essential for creating engaging user experiences:
Form Validation
Highlight fields with errors or success states during form submission.
Interactive UI
Create toggles, switches, and interactive elements that change state.
Theme Switching
Implement light/dark mode or custom color themes.
Dynamic Styling
Adjust layouts and styles based on user preferences or screen size.
CSS Manipulation Playground
Experiment with different CSS manipulation methods:
jQuery CSS Manipulation Playground
Try adding, removing, and toggling classes!
// CSS Playground function updateClassDisplay() { const classes = $("#playground-box").attr("class") || "none"; $("#playground-result").text("Current classes: " + classes); } $("#add-selected").click(function() { const className = $("#class-select").val(); $("#playground-box").addClass(className); updateClassDisplay(); }); $("#remove-selected").click(function() { const className = $("#class-select").val(); $("#playground-box").removeClass(className); updateClassDisplay(); }); $("#toggle-selected").click(function() { const className = $("#class-select").val(); $("#playground-box").toggleClass(className); updateClassDisplay(); }); $("#playground-reset").click(function() { $("#playground-box").removeClass(); updateClassDisplay(); }); // Initialize updateClassDisplay();
Best Practices
Follow these guidelines when working with jQuery CSS manipulation:
- Prefer classes over direct CSS - Use addClass/removeClass instead of css() when possible for better separation of concerns
- Cache selectors - Store frequently used jQuery objects in variables to improve performance
- Use CSS transitions - Combine jQuery class changes with CSS transitions for smooth animations
- Group class changes - Apply multiple classes at once instead of multiple method calls
- Use toggleClass for state changes - Perfect for elements that switch between two states
// Good practices for CSS manipulation // 1. Prefer classes over direct CSS // Instead of: $(".element").css("color", "red"); // Use: .highlight { color: red; } $(".element").addClass("highlight"); // 2. Cache selectors const $elements = $(".elements"); $elements.addClass("active"); // 3. Combine with CSS transitions .animated { transition: all 0.3s ease; } $(".element").addClass("animated active"); // 4. Group class changes // Instead of: $(".element").addClass("class1"); $(".element").addClass("class2"); // Use: $(".element").addClass("class1 class2"); // 5. Use toggleClass for state changes $(".toggle-button").click(function() { $(".target").toggleClass("active"); });