How to fix TypeError: removeClass is not a function in JavaScript

TypeError: removeClass is not a function in JavaScript

This article will explain why the TypeError: removeClass is not a function in JavaScript error appears and how we can fix it. Read on it now.

The reason of the TypeError: removeClass is not a function in JavaScript

Before getting to the ways to fix this error, we must determine the case that caused the error. This error appears when we use the removeClass() function, as shown below. Pay attention to the code.

Code:

var container = document.querySelector(".container");
container.removeClass("container");

Output:

Because this function is a function of jQuery, when you use it in pure Javascript, the error will appear because the program cannot find the function you are pointing to. So what to do in this case and still achieve the desired result?

How to fix the TypeError: removeClass is not a function in JavaScript? 

Classlist.remove() method

To remove the class of the element, we use the classList.remove() method with the element to remove the class passed as a parameter. This is pure Javascript usage and can be run as soon as you use this language. Just point to the element to remove the class and add this function.

Code:

var container = document.querySelector(".container");
container.classList.remove("container");

Output:

After using the remove() function on the container div tag, its class has been removed and is now just an empty class attribute like the output above. So our code ran usually, and the error no longer appeared. Or you can also refer to the below method to know how to use jQuery to fix it, not using pure Javascript to remove the class from the element.

Add JQuery to your project

Or you can also use the normal removeClass() function if you add jQuery to your HTML with the following line of code.

Code:

<script
src="https://code.jquery.com/jquery-3.6.2.slim.js"
integrity="sha256-OflJKW8Z8amEUuCaflBZJ4GOg4+JnNh9JdVfoV+6biw="
crossorigin="anonymous"></script>
<script type="module">
$(".container").removeClass("container");

Adding jQuery to the program allows you to use this function without any problems. First, you need to point to the div tag whose class is a container with its $ and class syntax. Then you add the removeClass() function to remove the class you need to remove. The result is the same as using classList.remove(). Good luck with these solutions.

Summary

In summary, the article has told you two ways to fix TypeError: removeClass is not a function in JavaScript, but adding jQuery will be the best way to use the removeClass() function.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *