jQuery CSS Classes
What are jQuery CSS Class Methods?
jQuery provides methods to add, remove, or toggle CSS classes dynamically, allowing you to change the style of elements without modifying the HTML or CSS file.
Why Use jQuery for CSS Classes?
✅ Dynamically change styles – Modify CSS without editing stylesheets.
✅ Easier than plain JavaScript – Simple, readable syntax.
✅ Improves interactivity – Create responsive and interactive web elements.
jQuery CSS Class Methods
Method | Description |
---|---|
addClass() | Adds one or more CSS classes to an element. |
removeClass() | Removes one or more CSS classes from an element. |
toggleClass() | Toggles between adding and removing a class. |
css() | Sets or gets individual CSS properties. |
Using jQuery CSS Class Methods
1. Add a Class to an Element – addClass()
👉 Example: Add a highlight class to a paragraph.
$(“#addClassBtn”).click(function() {
$(“#para”).addClass(“highlight”);
});
📌 What happens?
• Clicking the button adds the class, changing the paragraph’s background color.
2. Remove a Class from an Element – removeClass()
The removeClass() method removes a CSS class from an element.
👉 Example: Remove the highlight class from a paragraph.
$(“#removeClassBtn”).click(function() {
$(“#para”).removeClass(“highlight”);
});
📌 What happens?
• Clicking the button removes the highlight effect from the paragraph.
3. Toggle a Class – toggleClass()
The toggleClass() method switches between adding and removing a class every time the button is clicked.
👉 Example: Toggle the highlight class on a paragraph.
$(“#toggleClassBtn”).click(function() {
$(“#para”).toggleClass(“highlight”);
});
📌 What happens?
• If the class is not applied, it gets added.
• If the class is already applied, it gets removed.
Using jQuery CSS Class Methods
The css() method sets or retrieves individual CSS properties.
1. Get a CSS Property
👉 Example: Get the background color of a div.
$(“#getCssBtn”).click(function() {
alert(“Background color: ” + $(“#box”).css(“background-color”));
});
📌 What happens?
• Clicking the button displays the background color in an alert.
2. Set a CSS Property
👉 Example: Change the background color of a div.
$(“#setCssBtn”).click(function() {
$(“#box”).css(“background-color”, “blue”);
})
📌 What happens?
• Clicking the button changes the background color to blue.
3. Set Multiple CSS Properties
👉 Example: Change multiple styles at once.
$(“#setMultipleCssBtn”).click(function() {
$(“#box”).css({
“background-color”: “red”,
“width”: “300px”,
“height”: “200px”
});
});
📌 What happens?
• Clicking the button changes the background color, width, and height of the div.
Conclusion
🎯 addClass() – Adds one or more classes to an element.
🎯 removeClass() – Removes one or more classes from an element.
🎯 toggleClass() – Toggles a class on and off.
🎯 css() – Gets or sets CSS properties dynamically.