Solve - addClass is not a function Error in JavaScript


Borislav Hadzhiev

Last updated: Jul 23, 2022


Check out my new book

Solve - addClass is not a function Error #

The "addClass is not a function" error occurs for multiple reasons:

  • Calling the function on a value that is not a set of jQuery elements.
  • Misspelling addClass (it's case sensitive).
  • Placing the JS script tag above the HTML code that declares the DOM elements.
  • loading jQuery multiple times on the same page.

typeerror addclass is not a function

Here is an example of how the error occurs.

const box = document.getElementById('box'); // ⛔️ Uncaught TypeError: box.addClass is not a function box.addClass('blue');

We called the addClass method on a DOM element and not a set of jQuery elements.

To solve the "addClass is not a function" error, make sure to call the addClass method on a set of jQuery elements and place your JS script tag at the bottom of the body tag, after the DOM elements have been declared and jQuery is loaded.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box</div> <!-- ✅ load jQuery ✅ --> <script src="" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> <!-- ✅ Your JS script here ✅ --> <script src="index.js"></script> </body> </html>

Notice that we loaded jQuery and our own script (index.js) at the bottom of the body tag.

The order is important because had we loaded the scripts before the div was declared, we wouldn't be able to access the element in our index.js file.

Here is the code for the JS file.

const box = $('#box'); console.log(box); // 👉️ [div#box] // ✅ works box.addClass('blue');

We used the jQuery function to select the element with an id of box and used the addClass method to add a class to it.

Had we selected multiple elements, e.g. using a class selector, we would add the class to all the matching elements.

For example, if we have the following DOM elements:

<div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div>

And select the elements with a class of box:

const box = $('.box'); console.log(box); // 👉️ [,,] box.addClass('blue');

The addClass method adds the class to every DOM element that has a class name of box.

If the error persists, make sure you're spelling addClass correctly, as it is case-sensitive.

The order you load the scripts in is very important. You have to load the jQuery script only once and make sure it is loaded before your JavaScript code is ran.

If your code is ran before jQuery is loaded, you can't use any of the functionality jQuery provides in your code.

Use the search field on my Home Page to filter through my more than 3,000 articles.