How to add and remove CSS classes to an element using jQuery?


CSS classes perform a pivotal function in designing web pages and have a significant influence on their comprehensive facade. Since more significance is being placed on the aesthetics of pages, customizing web pages dynamically can greatly boost their value. At first observation, this task might appear to be intimidating, but utilizing jQuery, it becomes effortless to append or extract CSS classes from an HTML component in real-time, thereby providing an expeditious and effortless method of producing interactive and dynamic web pages. By affixing or eliminating CSS classes, we can reform the presentation of components on the spot, predicated on user actions or page occurrences, thereby refining the customization and user-friendliness of our web pages.

addClass() Method

The built-in jQuery method addClass() is used to provide each selected element new properties. Additionally, it can be used to modify the selected element's property.

Syntax

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

removeClass() Method

JQuery provides a built-in function called removeClass() that can be used to remove one or more class names from the specified element.

Syntax

$(selector).removeClass(className, function(index, currentClassName))

Approach

We are going to make use of the above discussed addClass() and removeClass() methods to add and remove CSS classes to an element respectively.

The code presented above is divided into three components, the HTML page, CSS stylesheet and finally the jQuery Script. Let us take a deep dive into all three one by one.

The HTML page consists of three components −

  • A <p> tag, which will act as the element on which we will add or remove the classes.

  • A “Add CSS Class” label button which we will use to add CSS class to the element

  • A “Remove CSS Class” label button which we will use to remove the CSS class from the element.

Now coming to the CSS part of things, we have used CSS to style a CSS called “p-style” with some specific properties such as background-color, padding, margin, color, and text-align. We are going to add and remove this class from the HTML element dynamically using jQuery.

Eventually, we have formulated the rationale to annex and rescind the CSS class in the script. In order to fulfill the versatile nature of this undertaking, we have employed the aforementioned addClass() and removeClass() functions. We have implemented the addClass() function to append the "p-style" class to the paragraph element dynamically. Conversely, we have executed the removeClass() function to eliminate the "p-style" class from the paragraph element dynamically. Upon close inspection of the code, one can observe that we have integrated the usage of these functions within the click events of the "Add CSS Class" and "Remove CSS Class" buttons correspondingly.

Example

The following is the complete code we are going to make use in this example −

<!DOCTYPE html>
<html>
<head>
   <title>How to add and remove CSS classes to an element using jQuery?</title>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <style>
      .p-style{
         background-color: black;
         padding: 3px;
         margin: 2px;
         color: white;
         text-align: center;
      }
   </style>
</head>
<body>
   <h4>How to add and remove CSS classes to an element using jQuery?</h4>
   <div>
      <p>This is some text.</p>
   </div>
   <br/>
   <div>
      <button id="add-class">Add CSS Class</button>
      <button id="remove-class">Remove CSS Class</button> 
   </div>
   <script>
      $(document).ready(function(){
         $('#add-class').click(function(){
            $('p').addClass('p-style');
         })
         $('#remove-class').click(function(){
            $('p').removeClass('p-style');
         })
      })
   </script>
</body>
</html>

Output

File output css class.gif is to be inserted here.

Conclusion

As a corollary, the ability to dynamically affix or detach CSS classifications to an HTML component through the utilization of jQuery can immensely augment the functionality and esthetics of a webpage. The implementation of this scripting vernacular empowers web designers to formulate interactive and visually captivating webpage layouts that ameliorate the user encounter. Besides, jQuery's all-purpose and elastic nature makes it an invaluable instrument in any web development enterprise, and its efficient handling of DOM manipulation tasks alleviates developers of time and labor. In essence, the tactful utilization of jQuery to attach or detach CSS classifications to HTML elements is an uncomplicated but potent methodology for achieving a refined and sophisticated webpage appearance.

Updated on: 10-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements