Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 5 - Manipulating CSS

5.2 Include-Exclude CSS Class

If you have any pre-defined CSS classes, you can include or exclude them for an element using the following functions:

  • element.classList.add('className'): Adds a class to the element.
  • element.classList.remove('className'): Removes a class from the element.
  • element.classList.toggle('className'): Toggles a class on the element.

For example:

<!DOCTYPE html>
    <title>Change CSS</title>
        .highlight {
            background-color: yellow;
        .emphasis {
            font-weight: bold;
            color: red;
    <p id="myParagraph">Hello, world!</p>
    const paragraph = document.getElementById('myParagraph');
    paragraph.classList.add('highlight'); // Adds the 'highlight' class
    paragraph.classList.remove('highlight'); // Removes the 'highlight' class
    paragraph.classList.toggle('emphasis'); // Toggles the 'emphasis' class

In this example, we defined two CSS classes: .highlight and .emphasis. We demonstrated how to add (classList.add()), remove (classList.remove()), and toggle (classList.toggle()) classes dynamically using JavaScript. Experiment with different classes to see how they affect the styling of the HTML element.