Adding, removing and checking if an element has a CSS class with jQuery
Posted December 16th, 2008 in Javascript
jQuery is a useful Javascript framework which simplifies cross browser Javascript development. This post looks at how to check what CSS class an element has with jQuery, and how to add and remove CSS classes from elements.
There is a full example of adding, removing and working out if a HTML element contains a CSS class with jQuery here: http://www.electrictoolbox.com/examples/jquery-classes.html
Adding a class
To add a class to an element do this:
$('#myelement').addClass('myclass');
To add it to multiple elements, for example all the "a" tags within a particular element you could do this:
$('#myelement a').addClass('myclass');
Removing a class
To remove a class from an element, do this:
$('#myelement').removeClass('myclass');
If the element doesn't already contain the class then nothing will happen, but nor will it result in an error. To remove a class from multiple elements, using the same example as in adding a class above, you could do this:
$('#myelement a').removeClass('myclass');
Checking to see if an element contains a class
An HTML element can contain multiple classes, e.g.:
<p class="foo bar baz"> ... </p>
and you can test if it contains a class with jQuery like so:
if($('#myelement').hasClass('myclass')) {
... do something ...
}
else {
... do something else ...
}
Example
There's a full example of this in action here: http://www.electrictoolbox.com/examples/jquery-classes.html This allows you to select which paragaph you would like to add and remove classes to or check if it contains a class.
Related posts:
- jQuery's toggleClass function (Friday, January 8th 2010)
- jQuery's document ready initialization (Friday, February 20th 2009)
- Dynamically get and set an elements content with jQuery (Sunday, January 11th 2009)
- How to check and uncheck a checkbox with jQuery (Friday, November 14th 2008)
- How to get and set form element values with jQuery (Thursday, November 13th 2008)
- Style an HTML form input with CSS and jQuery (Saturday, July 26th 2008)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

