Technology Encyclopedia Home >How to create and manipulate CSS classes in jQuery?

How to create and manipulate CSS classes in jQuery?

Creating and manipulating CSS classes in jQuery involves using methods like .addClass(), .removeClass(), .toggleClass(), and .css() to dynamically change the styles of HTML elements.

Creating CSS Classes

To create a CSS class, you typically define it in your CSS file or within a <style> tag in your HTML. For example:

/* Define a CSS class */
.highlight {
  background-color: yellow;
}

Manipulating CSS Classes with jQuery

  1. Adding a Class:
    Use .addClass() to add one or more classes to the selected elements.

    // Add the 'highlight' class to all paragraph elements
    $("p").addClass("highlight");
    
  2. Removing a Class:
    Use .removeClass() to remove one or more classes from the selected elements.

    // Remove the 'highlight' class from all paragraph elements
    $("p").removeClass("highlight");
    
  3. Toggling a Class:
    Use .toggleClass() to add the class if it's not present or remove it if it is.

    // Toggle the 'highlight' class on click of a button
    $("button").click(function(){
      $("p").toggleClass("highlight");
    });
    
  4. Changing CSS Directly:
    Use .css() to change the style properties directly, which can be useful for quick changes or specific styles not covered by classes.

    // Change the background color of all paragraph elements to blue
    $("p").css("background-color", "blue");
    

Example Scenario

Imagine you have a list of items, and you want to highlight the item that is currently hovered over by the mouse. You can achieve this using jQuery to add and remove a CSS class.

<!DOCTYPE html>
<html>
<head>
  <style>
    .highlight {
      background-color: yellow;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("li").hover(
        function() {
          $(this).addClass("highlight");
        }, 
        function() {
          $(this).removeClass("highlight");
        }
      );
    });
  </script>
</head>
<body>

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

</body>
</html>

In this example, when you hover over any list item, the highlight class is added, changing its background color to yellow. When the mouse leaves, the class is removed, restoring the original style.

Cloud-Related Recommendation

For dynamic web applications that require real-time styling changes or more complex interactions, consider using a cloud platform like Tencent Cloud to host your backend services. This allows for scalable and reliable handling of user interactions and data processing, ensuring a smooth user experience.