Paramclasses Academy - Blog

Tutorials Details

←
Post 6 of 15
→

What Is jQuery CSS Manipulation?

What Is jQuery CSS Manipulation?

October 14, 2026

What Is jQuery CSS Manipulation? Change CSS Properties, Classes and Styles

Introduction to jQuery CSS Manipulation

CSS controls the appearance of a webpage, including colors, fonts, spacing, borders and layouts. Sometimes, a website needs to change these styles dynamically in response to user actions.

For example, when a user clicks a button, you might want to change a heading's color, highlight a selected menu item, add a background to a card or switch between light and dark themes.

jQuery CSS manipulation makes these tasks easier by allowing you to read and change CSS properties and apply or remove CSS classes using simple methods.

In this tutorial, you will learn how to use jQuery's css(), addClass(), removeClass(), toggleClass() and hasClass() methods with practical examples.

What Is jQuery CSS Manipulation?

jQuery CSS manipulation is the process of accessing or changing the CSS styles of HTML elements using jQuery.

It allows developers to:

  • Change text and background colors.

  • Adjust font sizes and borders.

  • Add CSS classes to elements.

  • Remove existing CSS classes.

  • Toggle classes when users interact with a page.

  • Check whether an element contains a particular class.

  • Create interactive UI elements without manually editing the stylesheet each time.

For example, a button can add a highlight class to a card when clicked. The class can define the card's background, border and text color in CSS.

1. jQuery css() Method

The css() method is used to get or set CSS properties of selected HTML elements.

Syntax

Get a CSS property:

$(selector).css("propertyName");

Set a single CSS property:

$(selector).css("propertyName", "value");

Set multiple CSS properties:

$(selector).css({
    propertyName: "value",
    anotherProperty: "value"
});

Example: Change Text Color

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery CSS Example</title>
</head>
<body>

    <h2 id="heading">Welcome to jQuery</h2>

    <button id="changeColor">Change Color</button>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $(document).ready(function () {
            $("#changeColor").on("click", function () {
                $("#heading").css("color", "blue");
            });
        });
    </script>

</body>
</html>

Expected Output

Initially, the heading uses its normal text color. When the user clicks Change Color, the heading becomes blue.

Explanation

  1. $("#changeColor") selects the button.

  2. .on("click", ...) attaches a click event handler.

  3. $("#heading") selects the heading.

  4. .css("color", "blue") changes its text color to blue.

Example: Change Multiple CSS Properties

<p id="message">This is a sample paragraph.</p>

<button id="styleButton">Apply Styles</button>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script>
    $(document).ready(function () {
        $("#styleButton").on("click", function () {
            $("#message").css({
                "color": "white",
                "background-color": "blue",
                "font-size": "20px",
                "padding": "15px",
                "border-radius": "8px"
            });
        });
    });
</script>

Expected Output

After clicking the button, the paragraph has white text, a blue background, larger font size, padding and rounded corners.

Example: Get a CSS Property

let textColor = $("#message").css("color");

console.log(textColor);

This retrieves the element's computed text color. The browser may return a value such as rgb(255, 255, 255) rather than the color name originally used in the stylesheet.

Where Is css() Used?

  • Changing text colors dynamically.

  • Highlighting important information.

  • Updating backgrounds and borders.

  • Adjusting the appearance of selected elements.

  • Applying simple interactive styles.

2. jQuery addClass() Method

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

Instead of setting many CSS properties individually with css(), you can define a reusable class in your stylesheet and apply it using jQuery.

Syntax

$(selector).addClass("className");

To add multiple classes:

$(selector).addClass("classOne classTwo");

Example: Add a Highlight Class

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery addClass Example</title>

    <style>
        .highlight {
            color: white;
            background-color: #1769aa;
            padding: 15px;
            border-radius: 8px;
        }
    </style>
</head>
<body>

    <p id="description">Learn jQuery CSS manipulation.</p>

    <button id="highlightButton">Highlight Text</button>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $(document).ready(function () {
            $("#highlightButton").on("click", function () {
                $("#description").addClass("highlight");
            });
        });
    </script>

</body>
</html>

Expected Output

When the user clicks Highlight Text, the paragraph receives the styles defined in the highlight class.

Explanation

  • .highlight defines the desired appearance in CSS.

  • addClass("highlight") adds the class to the paragraph.

  • The browser applies the styles associated with that class.

Why Use addClass()?

It is useful when you want to reuse styles across multiple elements or keep styling separate from JavaScript logic.

3. jQuery removeClass() Method

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

Syntax

$(selector).removeClass("className");

To remove multiple classes:

$(selector).removeClass("classOne classTwo");

Example: Remove a Highlight Class

<p id="text" class="highlight">This paragraph is highlighted.</p>

<button id="removeHighlight">Remove Highlight</button>

<style>
    .highlight {
        background-color: yellow;
        color: black;
        padding: 10px;
    }
</style>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script>
    $(document).ready(function () {
        $("#removeHighlight").on("click", function () {
            $("#text").removeClass("highlight");
        });
    });
</script>

Expected Output

The paragraph initially has a yellow background. After clicking the button, the highlight class is removed and its associated styles no longer apply.

Practical Uses

  • Removing a selected menu style.

  • Clearing validation highlighting.

  • Removing a temporary warning style.

  • Resetting a component to its normal appearance.

4. jQuery toggleClass() Method

The toggleClass() method adds a class if it is absent and removes it if it is already present.

It is useful when a user needs to switch between two visual states.

Syntax

$(selector).toggleClass("className");

Example: Toggle a Highlight Class

<p id="toggleText">Click the button to change my appearance.</p>

<button id="toggleButton">Toggle Highlight</button>

<style>
    .highlight {
        color: white;
        background-color: green;
        padding: 15px;
    }
</style>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script>
    $(document).ready(function () {
        $("#toggleButton").on("click", function () {
            $("#toggleText").toggleClass("highlight");
        });
    });
</script>

Expected Output

  • On the first click, the highlight class is added.

  • On the second click, the class is removed.

  • Further clicks continue switching between the two states.

Explanation

toggleClass() checks whether the selected element has the specified class and switches its presence accordingly.

Practical Uses

  • Opening and closing navigation menus.

  • Highlighting selected cards.

  • Switching between active and inactive states.

  • Creating simple theme toggles.

5. jQuery hasClass() Method

The hasClass() method checks whether at least one selected element has a specified class.

It returns true if the class exists on a matching element, otherwise it returns false.

Syntax

$(selector).hasClass("className");

Example: Check a CSS Class

<p id="status" class="active">Account Status</p>

<button id="checkButton">Check Status</button>

<p id="result"></p>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script>
    $(document).ready(function () {
        $("#checkButton").on("click", function () {
            if ($("#status").hasClass("active")) {
                $("#result").text("The account is active.");
            } else {
                $("#result").text("The account is not active.");
            }
        });
    });
</script>

Expected Output

Because the paragraph has the active class, clicking the button displays:

The account is active.

Explanation

  1. hasClass("active") checks whether the class exists.

  2. If it returns true, the first message is displayed.

  3. Otherwise, the alternative message is displayed.

Where Is hasClass() Used?

  • Checking whether a menu item is active.

  • Determining whether a component is selected.

  • Checking whether an element has a warning or error class.

  • Updating the interface based on the current state.

6. Difference Between jQuery CSS Methods

Method Purpose
css() Gets or sets CSS properties.
addClass() Adds one or more CSS classes.
removeClass() Removes one or more CSS classes.
toggleClass() Adds or removes a class according to its current state.
hasClass() Checks whether an element has a specified class.

Best practice: Use css() for small, direct style changes. For reusable styles involving several properties, CSS classes with addClass(), removeClass() and toggleClass() are usually easier to maintain.

7. Complete Practical Example: Interactive Profile Card

Let's build a small profile card that allows users to change its appearance, highlight it and reset its styling.

Complete HTML, CSS and jQuery Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>jQuery CSS Manipulation Project</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            padding: 30px;
            text-align: center;
        }

        .profile-card {
            max-width: 320px;
            margin: 20px auto;
            padding: 25px;
            background: white;
            border: 2px solid #d6deeb;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .profile-card.highlight {
            background: #e3f2fd;
            border-color: #1769aa;
        }

        .profile-card.dark-mode {
            background: #202938;
            color: white;
            border-color: #202938;
        }

        button {
            padding: 10px 14px;
            margin: 5px;
            border: none;
            border-radius: 6px;
            background: #1769aa;
            color: white;
            cursor: pointer;
        }

        button:hover {
            background: #0e4778;
        }
    </style>
</head>
<body>

    <h1>Interactive Profile Card</h1>

    <div id="profileCard" class="profile-card">
        <h2 id="profileName">Rahul Sharma</h2>
        <p>Web Developer</p>
        <p>Learning jQuery step by step.</p>
    </div>

    <button id="highlightButton">Highlight Card</button>
    <button id="darkButton">Toggle Dark Mode</button>
    <button id="resetButton">Reset Card</button>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $(document).ready(function () {

            // Toggle the highlight class
            $("#highlightButton").on("click", function () {
                $("#profileCard").toggleClass("highlight");
            });

            // Toggle dark mode
            $("#darkButton").on("click", function () {
                $("#profileCard").toggleClass("dark-mode");
            });

            // Reset classes and inline styles
            $("#resetButton").on("click", function () {
                $("#profileCard")
                    .removeClass("highlight dark-mode")
                    .removeAttr("style");
            });

        });
    </script>

</body>
</html>

How to Run This Project

  1. Open Visual Studio Code.

  2. Create a file named jquery-css-manipulation.html.

  3. Copy and paste the complete code.

  4. Save the file.

  5. Open it in a browser or use Live Server.

  6. Click each button to test the different styles.

Expected Output

  • Highlight Card: Switches the card's highlight style on or off.

  • Toggle Dark Mode: Switches the card between its normal and dark appearance.

  • Reset Card: Removes the two interactive classes and any inline style attribute from the card.

What You Learn from This Project

This project demonstrates how jQuery can work with CSS classes to control the appearance of webpage components.

Instead of repeatedly setting many individual CSS properties in JavaScript, you can define styles in CSS and use jQuery to change which classes are applied.

8. Common Mistakes in jQuery CSS Manipulation

Mistake 1: Using the Wrong Selector

$("#heading").css("color", "red");

If the element does not have id="heading", the style change will not affect the intended element.

Solution: Verify that the selector matches the HTML.

Mistake 2: Forgetting the CSS Class Dot

Correct:

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

Do not include the dot in the class name passed to addClass().

Mistake 3: Confusing addClass() and css()

addClass() applies a predefined CSS class. css() gets or sets CSS property values directly.

Solution: Use classes for reusable sets of styles and css() for individual property changes when appropriate.

Mistake 4: Overwriting Styles Unintentionally

Setting an inline style with css() can override a style defined in a stylesheet.

Solution: Use classes when you need consistent styling across several elements.

Mistake 5: Forgetting That hasClass() Returns a Boolean

The hasClass() method returns true or false, not the class name.

Solution: Use it inside a condition when checking an element's state.

9. Best Practices for jQuery CSS Manipulation

  • Keep most reusable styles in CSS files.

  • Use meaningful class names such as active, highlight and error.

  • Prefer class manipulation for multiple related style changes.

  • Use hasClass() when logic depends on the current class state.

  • Avoid repeatedly overwriting styles with inline CSS when a class would be more maintainable.

  • Test your interface on mobile and desktop screens.

  • Maintain accessible color contrast when changing text and background colors.

  • Use clear selectors and keep event handlers organized.

10. Frequently Asked Questions (FAQs)

1. What is jQuery CSS manipulation?

It is the process of reading or changing the CSS properties and classes of HTML elements using jQuery.

2. What is the use of the css() method?

The css() method gets a computed CSS property value or sets one or more CSS properties on selected elements.

3. What is the difference between addClass() and removeClass()?

addClass() adds the specified class to an element, while removeClass() removes it.

4. What does toggleClass() do?

It adds a class if the class is absent and removes it if the class is present.

5. What is the purpose of hasClass()?

It checks whether a selected element has a particular CSS class and returns a Boolean value.

6. Can jQuery change multiple CSS properties at once?

Yes. You can pass an object containing several CSS property and value pairs to css().

7. Is it better to use css() or addClass()?

Use css() for direct property changes. Use CSS classes when several styles should be reused or switched together.

8. Can jQuery change a background color?

Yes. For example:

$("#box").css("background-color", "yellow");

9. Can jQuery add multiple classes?

Yes.

$("#box").addClass("active highlight");

10. Can jQuery remove multiple classes?

Yes.

$("#box").removeClass("active highlight");

11. jQuery CSS Manipulation Interview Questions

  1. What is CSS manipulation in jQuery?

  2. Explain the css() method with an example.

  3. What is the difference between addClass() and removeClass()?

  4. How does toggleClass() work?

  5. What does hasClass() return?

  6. How can you change several CSS properties using jQuery?

  7. What is the difference between inline styles and CSS classes?

  8. How can you create a dark-mode toggle using jQuery?

  9. How do you check whether an element has the active class?

  10. Why are CSS classes useful for reusable styles?

12. Practice Exercises

Try these exercises to improve your understanding of jQuery CSS manipulation.

  1. Change a heading's text color when a button is clicked.

  2. Change the background color of a paragraph using css().

  3. Apply a highlight class to a card using addClass().

  4. Remove the highlight class using removeClass().

  5. Create a button that toggles a card's appearance.

  6. Use hasClass() to check whether an element is active.

  7. Change multiple CSS properties in one css() call.

  8. Build a light-mode and dark-mode toggle for a card.

  9. Create a selected state for navigation menu items.

  10. Build a profile card with Highlight, Dark Mode and Reset buttons.

13. Multiple-Choice Questions (MCQs)

1. Which jQuery method changes CSS properties directly?

A. text()

B. css()

C. val()

D. append()

Correct Answer: B. css()

2. Which method adds a CSS class?

A. removeClass()

B. hasClass()

C. addClass()

D. empty()

Correct Answer: C. addClass()

3. Which method removes a CSS class?

A. removeClass()

B. toggleClass()

C. css()

D. clone()

Correct Answer: A. removeClass()

4. Which method checks whether an element has a particular class?

A. addClass()

B. hasClass()

C. hide()

D. html()

Correct Answer: B. hasClass()

5. Which method can switch a CSS class on and off?

A. val()

B. append()

C. toggleClass()

D. remove()

Correct Answer: C. toggleClass()

6. Which method can set several CSS properties in a single call?

A. css()

B. hasClass()

C. removeClass()

D. text()

Correct Answer: A. css()

Conclusion

jQuery CSS manipulation helps developers change the appearance of HTML elements without manually rewriting styles for every interaction.

In this tutorial, you learned how to use css(), addClass(), removeClass(), toggleClass() and hasClass() with practical examples.

These methods are useful for building interactive cards, navigation menus, theme toggles, selected states and dynamic user interfaces.

Practice the examples and try combining jQuery events with CSS class manipulation to build more interactive webpages.

←
Post 6 of 15
→