-1

I would like to access html-objects in a html file from a js file with JQuery like it is described in w3schools.

I have these two files:

test.html

<!DOCTYPE html>
<html>
<head>
    <title>Beispiel Titel</title>

    <script type="text/javascript" src="test.js" ></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>

<div id="test"> dummy </div>

<!-- <script>
  $('#test').text("huhu");
</script> -->

</body>
</html>

and test.js

$(document).ready(function(){
  $('#test').text("huhu");
});

If I uncomment the snippet inside the html file it works. But why it do not work from the js file?

Alex44
  • 3,597
  • 7
  • 39
  • 56
  • 5
    Did you try reordering your script tags so the `test.js` is after the `jquery.min.js`? My first guess is that test.js is trying to reference `$` which doesn't exist yet because the page is processed in order. – jeffjenx Jun 10 '19 at 15:18
  • Did you do soma basic debugging and check the console? You will get an error that you can look up quite easily. – j08691 Jun 10 '19 at 15:23
  • I only use gedit. But I spend some hours in searching for a simple example and did not found this hint. It's a beginners problem. The books I have even does not provide an example regarding this. – Alex44 Jun 10 '19 at 15:30

2 Answers2

4

Change the order of the files. This is because the code in js file will run even before the jquery is loaded.Instead you need to first load jquery and then the relevant js file

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="test.js" ></script>
brk
  • 48,835
  • 10
  • 56
  • 78
1

You need to load your script after loading jquery. Jquery is not loaded, so you are getting $ not defined (check your developer console with f12 to see errors)

Cal Irvine
  • 1,104
  • 8
  • 17