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>
<html>
<head>
    <title>Change CSS</title>
    <style>
        .highlight {
            background-color: yellow;
        }
        .emphasis {
            font-weight: bold;
            color: red;
        }
    </style>
</head>
<body>
    <p id="myParagraph">Hello, world!</p>
</body>
<script>
    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
</script>
</html>

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.