You are running the code when the DOM isn't ready yet.
There are 2 solutions:
Solution One:
Add the Javascript after the elements it affects. Preferably as far down the page as possible.
Doing this is not always possible, but it is suggested by YUI for speeding up your website.
<html>
<head>
<script src="../jquery.js" type="text/javascript"> </script>
</head>
<body>
<p class="demo">a paragraph</p>
<script type="text/javascript">
// This is after .demo
$(".demo").click(function() {
alert("JavaScript Demo");
});
</script>
</body>
</html>
Solution Two:
Wrap your script in a doc ready. In jQuery there are several forms. The quickest to type is $(function() { ... });:
<html>
<head>
<script src="../jquery.js" type="text/javascript"> </script>
<script type="text/javascript">
// doc ready
$(function() {
$(".demo").click(function() {
alert("JavaScript Demo");
});
});
</script>
</head>
<body>
<p class="demo">a paragraph</p>
</body>
</html>