Adding, removing and checking if an element has a CSS class with jQuery

Posted 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: https://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: https://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:


Comments