Home > front end >  Uncaught TypeError: $(...).addClass is not a function
Uncaught TypeError: $(...).addClass is not a function

Time:01-23

I have a special case here... In my code, the jQuery is initialised and also $(...).on('click', function() {}) is working fine. But when I am trying to use .addClass function I am getting that error message.

code:

<script>
   $('#[email protected]').on('click', function () {
   console.log('service @subservice.Name clicked');
   $('#[email protected]').addClass('bg-success');
   });
</script>

So, everything is working, but .addClass function. Ideas?

I tried different versions of jQuery, but no success.

CodePudding user response:

There's only one way I can imagine this happening if you're using an unmodified jQuery: If you load something else that takes over the $ symbol after the event handler is hooked up. Here's an example using PrototypeJS:

.x {
    color: green;
}
<div id="target">Click me</div>

<!-- Load jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Your code -->
<script>
$("#target").on("click", function() {
    $("#target").addClass("x");
});
</script>

<!-- Load PrototypeJS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.min.js"></script>

If that's what's happening, ideally consider using only jQuery or the other library on the page, not both. But if you can't do that (or at least, not right now), you can wrap your code in a function that ensures $ refers to jQuery:

.x {
    color: green;
}
<div id="target">Click me</div>

<!-- Load jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Your code -->
<script>
(function($) {
    $("#target").on("click", function() {
        $("#target").addClass("x");
    });
})(jQuery);
</script>

<!-- Load PrototypeJS -- doesn't mess things up -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.min.js"></script>

Notice how the function accepts a parameter called $, and we call it supplying jQuery as the argument for that parameter. Then it doesn't matter what the global $ refers to, the one in that code refers to jQuery.

  • Related