0

I am very new to jQuery, literally just trying to get it to work for the first time. Only the alert box works, but none of the other very simple methods I am trying out. Here are the files:

HTML:

<!DOCTYPE HTML>
  <html>
    <head>
      <title>jquery</title>
      <script type="text/javascript" src="jquery-3.1.0.min.js"></script>
      <script type="text/javascript" src="myJavaScript.js"></script>
  </head>
  <body>

    <h1 id="title">This is a title</h1>

    <p> This is some sample text.</p>
  </body>
</html>

JavaScript file:

$(document).ready(function (){alert("this works!")});

$("#title").text("but this is not not working");

As you can see the example can't be simpler. I have off course downloaded the jquery-3.1.0.min.js file and put it in the same folder as the html. If I comment out the link, the alert stops working, so I now the file is being referenced OK. Why is the second line of jQuery not working? Many thanks, P

Paul
  • 1,045
  • 4
  • 22
  • 46
  • [When should I use jQuery's document.ready function?](http://stackoverflow.com/a/13062512/3499595) Also there is a kind of a rule to place the custom scripts just before `

    ` that way the HTML is correctly parsed before the scripts are executed.

    – yuriy636 Sep 04 '16 at 15:24
  • Any DOM operation belongs inside `$(document).ready(function(){`…`});`, not outside. – Sebastian Simon Sep 04 '16 at 15:28

1 Answers1

0

Because the DOM(the entire structure of your application) isn't loaded yet. You need to use a $(document).ready(makes sure the DOM is loaded before running jQuery code) or an event handler to make the change visible.

luissimo
  • 866
  • 2
  • 8
  • 28