When I was creating my first jquery project in 2012, I got a weird referenceerror: $ is not defined. I was very excited with JQuery but this error broke my heart. I was tearing my hair because I was doing everything right and still getting the error. This is a common mistake done by beginners. In this article we will look at the ways to resolve it.
There are few reasons for $ not defined error –
$('#selector')
before loading jquery script on webpage.The below code snippet will raise “$ is not defined” error because we are loading jquery after using $ function.
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<p>jQuery will raise error</p>
<script>
$('p').html('jQuery runs fine here');
</script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>
HTMLCopy
To resolve the error and correct this code, we need to shift our js after jquery script. So, the below code will run fine.
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<p>jQuery will raise error</p>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('p').html('jQuery runs fine here');
</script>
</body>
</html>
#html-css #jquery #jquery error #jquery short