JavaScript·100 questions

[ITEM 3] QUESTION: How to work with element classes?

Answer

Managing CSS classes in JavaScript is a key tool for creating dynamic user interfaces, animations, and switching color themes. The most modern, convenient, and efficient way to work with classes is the classList property, which is a special DOMTokenList object.

The classList object provides a rich set of methods for targeted modification of an element's classes. The classList.add('className') method adds one or more new classes to an element if they are not already there. The classList.remove('className') method removes the specified class, making it easy to hide elements or reset states. The universal classList.toggle('className') method works like a switch: if the element has the class, it is removed; if not, it is added. This is extremely convenient for implementing drop-down menus, modal windows, or theme switching.

To check for the presence of a specific class, the classList.contains('className') method is used, returning a boolean true or false, which is indispensable in conditional statements. Meanwhile, the classList.replace(oldClass, newClass) method allows replacing an existing class with a new one in a single statement, eliminating the need to write combinations of remove and add.

The historical approach involved using the className property, which returns or sets the entire string of element classes at once. Working with className is less convenient because when changing a single class, you have to manually parse and concatenate the entire string to avoid overwriting the remaining styles. Unlike it, classList eliminates these problems, allowing you to manage each class isolated and safely.

For example, to implement an interactive "like" button, it is enough to attach an event handler to it that will call el.classList.toggle('is-active'). This makes the code minimalist, readable, and easily maintainable in any project.

Was this answer helpful?

More questions in this topic

Related questions from other topics