Solve - addClass is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Adetunji Paul

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.

index.js
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.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box</div> <!-- โœ… load jQuery โœ… --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" 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.

index.js
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 of the matched elements.

For example, if we had the following DOM elements:

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

And selected the elements with a class of box:

index.js
const box = $('.box'); console.log(box); // ๐Ÿ‘‰๏ธ [div.box, div.box, div.box] box.addClass('blue');

The addClass methods 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee