jQuery: the addClass() and removeClass() methods

As their name says, the jQuery's addClass() and removeClass() methods simply add and remove classes on a given element, respectively. However, they differ greatly in how they work. In fact, the addClass() method makes use of the className property and some regular expressions to attach one or more classes to an element. Example:

$('#test').addClass('foo'); // adds the class 'foo'
$('#bar').addClass('foo bar'); // adds the classes 'foo' and 'bar'

You can attach multiple classes to an element by simply providing a space-separated list of valid class names. But the real interesting thing happens when you remove a class through the removeClass() method. Example:

 $('#test').removeClass('foo'); // removes the class 'foo'
$('#bar').removeClass('foo bar'); // removes the classes 'foo' and 'bar'

To remove classes, jQuery doesn't use the core DOM method removeAttribute() because of the backward compatibility with Internet Explorer 6. Instead, it uses regular expressions to replace the value of the class attribute with an empty string. If you take a look at the class attribute after using this method, you will see something like this:

<div id="test" class=""></div>
<div id="bar" class=""></div>

As you can see, the class attribute is still present in the DOM, but it has no impact on page layout because its value is empty.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.