In Manipulating Element Attributes with jQuery, you explored 2 jQuery methods for working with element attributes: attr()
to read, add, and change attributes, and removeAttr()
to remove attributes.
In this tutorial you’ll look at some jQuery methods for working specifically with the class
attributes of elements:
hasClass()
to check if an element has a certain classaddClass()
to add a class to an elementremoveClass()
to remove a class from an elementtoggleClass()
to add a class to an element if it doesn’t already have it, or remove a class if it does
While you can use attr()
and removeAttr()
to work with classes, these class-specific methods are more useful because:
- They’re easier to use on classes
- You tend to work with CSS classes a lot with jQuery, and
class
attribute values often contain multiple class names, making them more complex to deal with than most other attributes.
Let’s take a look at each of these methods in turn.