Length: 10 minutes
Summary
let element = document.querySelector('#id-name');
element.classList.add('class-name');
Details
To add a CSS class to an element, first you’ll want to select an element using querySelector() and save it to a variable. Replace #id-name
with the actual selector you want to use.
let element = document.querySelector('#id-name');
Next, you’ll want to use the classList and the add() function to add a class name. Replace class-name
with the actual class name you want to use (and make sure the class already exists in your CSS code).
let element = document.querySelector('#id-name');
element.classList.add('class-name');
Adding multiple classes
You can insert more than one class by passing in more than one class name separated by commas, like this:
let element = document.querySelector('#id-name');
element.classList.add('class-name-1', 'class-name-2');
Demo
Exercises
Recreate the JS code from the Demo section in your JS file.