You are using $
which is usually the global variable that jQuery sets when you load it, for example, using:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
... tus funciones // supongamos que esto es el script de tu pregunta
<script>
</head>
<body>
... shake your body ...
</body>
</html>
If you do not have $
in the global scope, your script will throw that error.
Suppose for example that you have the following code
var ManipulaDOM = function() {
this.borraElemento = function(selector) {
$(selector).remove();
};
};
that does not throw any error. But if you do:
var manipulador = new ManipulaDOM();
manipulador.borraElemento('#mi_div');
The javascript interpreter will invoke borraElemento
. Inside is found with $
that is not defined within borraElemento
. Keep looking for it by going up in the Stack. But neither is it defined in ManipulaDOM
. Keep going up the stack until it reaches the global scope, and if it turns out that window.$
is not defined, then it throws that error.
Although most of the websites that use jQuery put it in the <head>
of the document, it is also possible to put it at the end of the <body>
(for all those good practices that explain that the scripts are blocking and delay the DOM load). You could do:
<body>
<div id="mi_div">hola</div>
<script>
var ManipulaDOM = function() {
this.borraElemento = function(selector) {
$(selector).remove();
};
};
</script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
var manipulador = new ManipulaDOM();
manipulador.borraElemento('#mi_div');
</script>
</body>
And that would not be an error, because when you declare the first, you still do not occupy $
and when you invoke it, at that height $
is already in the global scope.
Stripe for the sum: Make sure that jQuery has loaded before to use functions that use $
. And if those functions manipulate the DOM, also make sure to wrap the entire block in $(document).ready(function() { ... });
or any of its variants.