CSS Class Manipulation with jQuery

Each HTML element can have a CSS class attribute which controls the look and feel of the element. The CSS class of an element corresponds to the style sheet definition. Style sheets are managed separately from HTML or any other presentation code for better maintainability. Often need arises to manipulate these class attributes to assign or remove new CSS classes dynamically. jQuery caters this need by providing us methods to inspect and manipulate CSS classes assigned to the HTML elements. This article would explores the options available for manipulating the CSS properties using the jQuery.

also read:

The following code example uses jQuery to assign new CSS class, remove an assigned CSS class, toggle adding/removing CSS class and inspects for the CSS class.

<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
.paragraph {font-size:20px;color:#0000cc}
<script type="text/javascript">
$(document).ready(function() {



<h1>CSS Class Manipulation with jQuery</h1>
<p>This is a simple paragraph text.
   When 'Change' button is clicked this paragraph
   CSS class will be changed.</p>

<input type="button" value="Change" id="changeBtn"/>
<input type="button" value="Remove" id="removeBtn"/>
<input type="button" value="Toggle" id="toggleBtn"/>
<input type="button" value="Has Class?" id="hasClassBtn"/>


Let’s discuss about the methods we used in the above example:


The .addClass adds the specified CSS classes to the matched elements. The elements to add CSS class can be matched using selector syntax. The following code snippet adds the CSS class to all the paragraphs in the document.




The .removeClass removes one or more CSS classes from the matched elements. The elements can be matched with selector syntax. The following code snippet removes the CSS class from all the paragraphs.


We can also specify multiple CSS classes to remove from matched elements as shown below:

$("p").removeClass('paragraph anyotherclass highlightclass');



The .toggleClass either adds or removes the CSS classes from the matched elements based on whether the class already present or not. In the below code example, if CSS class is not present then the CSS class is added, if it is present it will be removed.




The .hasClass returns boolean value on whether any matched elements have the specified class or not.


We can manipulate the CSS classes from jQuery using .addClass, .removeClass, .toggleClass and .hasClass methods. These methods provide flexible ways to dynamically add or remove CSS classes to the elements to control the look and feel of the elements.

also read:

If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on jQuery and Java topics, please subscribe here.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!