Paul Paul - 3 months ago 13
HTML Question

Basic code not working with jQuery

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

Answer

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.