Wed Oct 20 2021·2 min read
Photo by Adetunji Paul
The "addClass is not a function" error occurs for multiple reasons:
addClass(it's case sensitive).
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
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="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
divwas declared, we wouldn't be able to access the element in our
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
addClass method to add a class to it.
For example, if we had the following DOM elements:
<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
const box = $('.box'); console.log(box); // 👉️ [div.box, div.box, div.box] box.addClass('blue');
addClass methods adds the class to every DOM element that has a class name
addClasscorrectly, as it is case sensitive.
If your code is ran before jQuery is loaded, you can't use any of the functionality jQuery provides in your code.
I'll send you 1 email a week with links to all of the articles I've written that week