classList.add doesn’t work in JavaScript

Sometimes when you want to add a class with classList.add() it may not work.

Here are the most common reasons:

  • You’re using an outdated browser or one that doesn’t support JavaScript.
  • You’ve provided the wrong class name. This should add the class but won’t change the element styles.
  • You’ve provided the wrong element ID.
  • You’ve used it wrong. For example, instead of something like element.classList.add(‘newClass’) you tried to use something like element.classList.add = ‘newClass’.

Here’s a ready-to-implement, working example:

<style>
    .green {
        background: green;
    }
</style>

<div id="myElement" style="width:60px; height: 60px"></div>

<script>
    document.getElementById('myElement').classList.add('green');
</script>

Output: