Last updated .
In this document I will give a concise description of jQuery and what it is good for.
At the end, I am going to show case the development of a pluggable menu with jQuery.
The simplest way to get started is to download the jQuery javascript file from jQuery.com.
The contents of this file should be run when the page loads. The preferred way to accomplish that is to simply reference the file in a script tag. This script tag should be placed in the body tag below the structural markup, but before any other script tags, like this:
<body>
<p>Here goes all the markup and content...</p>
<script src="jquery-2.1.4.js"></script>
<script>Some more script that may use jQuery...</script>
</body>
As you can see, the file name reflects the version number, so the actual file name is likely to be different from the one shown.
The inclusion of the jQuery script adds a property to the window object with the name jQuery. An alias for the same property is $. So, the following three code lines are equivalent:
console.log(window.jQuery.length);
console.log(jQuery.length);
console.log($.length);
Though javascript does not know the concept of class, I am using the term here conceptually to denote the concept of a prototype from which objects are created. An instance of the jQuery class is returned when you call the jQuery function. This function is used to select a set of DOM elements, which are then contained in the returned jQuery object, like this:
<p>A paragraph</p>
<p>Another paragraph</p>
<script>
var selection = jQuery("p"); // same as $("p");
console.log(selection.length); // 2
console.log(selection[1].innerHTML); // Another paragraph
</script>
The first line in the above code selects all p elements in the document, contained in a jQuery object (the selection variable). These three lines of code are equivalent to the following code that does not use jQuery:
var selection = document.getElementsByTagName("p");
console.log(selection.length);
console.log(selection[1].innerHTML);
It would appear that you could avoid jQuery and just as well use the functionality exposed by the document object to achieve this result. But this is a really simple example. jQuery lets you select elements in precise ways with a wide range of selectors. That is what the next chapter is about.