Yes, you can change CSS with JavaScript, but it’s better to use classes to let CSS handle CSS tasks.
To add a class, use the add
method within the classList
property:
Example:
To add multiple classes, pass additional arguments:
To remove a class, use the remove
method:
To check if a class exists, use the contains
method:
Example:
To toggle a class, use the toggle
method:
Summary
- Add a class:
Element.classList.add('className')
- Add multiple classes:
Element.classList.add('firstClass', 'secondClass'
- Remove a class:
Element.classList.remove('className')
- Remove multiple classes:
Element.classList.remove('firstClass', 'secondClass')
- Check if a class exists:
Element.classList.contains('className')
- Toggle a class:
Element.classList.toggle('className')