Classes and Styles

Learn how to dynamically add classes and styles to a selection.

In this lesson, we will learn how to properly apply classes and styles to an element. As we have learned, we can use the attr() method to apply attributes. This includes the class and style attributes. It is handy, but it is not the ideal method for adding classes.

The problem with the attr() method

We should be aware of one caveat when working with the attr() method. The attr() method will override any existing value of an attribute if it already exists.

For example, let’s say we wanted to add an additional class. That is a problem. The second class will remove the first class. Let me show you what happens if we attempt to chain the attr() method multiple times for the same HTML attribute.

Get hands-on with 1200+ tech skills courses.