1024px-Flatirons_Winter_Sunrise_edit_2

This post will demonstrate two approaches for manipulating the classes of an HTML element. The first uses the plain javascript property classList and the second uses jQuery, a popular javascript library. To begin, consider the following document:

The document has one button with an onclick event to toggle the color of the button. The CSS defines classes to set the background color:

The only thing left to do is to implement the toggleColor() function in javascript.

classList

Every element has a classList property containing its class attributes. This property provides methods that make it straightforward to add or remove a class.

http://codepen.io/qualitydixon/pen/GoeOOP

The above example uses three methods provided by classList.

  • contains() – Returns true if the element has the provided class, else returns false.
  • add() – Adds the given class to the element. This is ignored if the element already contains the specified class.
  • remove() – The provided class is removed from the element, if present.

An even simpler way to accomplish the same thing is to use the toggle() method. Which will add the provided class if it is not present, or remove it if it is:

http://codepen.io/qualitydixon/pen/BjbmQM

When working with multiple classes, simply comma separate the classes in separate strings:

The only potential drawback to this approach is it was introduced in HTML5 and may not be supported if you are working with older browsers.

jQuery

jQuery provides methods that function almost exactly like those shown above, but you get the added bonus of using jQuery’s shorthand for selecting elements. Here is the toggleColor() function written in jQuery:

http://codepen.io/qualitydixon/pen/KVEyjg?editors=1001

You could also use addClass(), removeClass(), and hasClass() to construct toggleColor() in the same manner as our first example. Note that to add multiple classes simply space separate the classes in the same string. For example:

That’s it! Now you’re well equipped to dynamically set the appearance of DOM elements. Happy coding!