As its name suggests, jQuery's core functionality is a query. We select (query) elements on a page - for example all
<h2>s, or, the third list item in a specific unordered list - and gather information about the elements or modify the elements in some manner.
To use jQuery, we first load, via a
<script> tag, the jQuery library. We can do this in one of two ways: either by downloading jQuery and hosting it locally, or by linking to a CDN-hosted version of the library. (A CDN, or content delivery network, is typically a large distributed network of servers that host a resource available for sharing. Both Google and jQuery host publicly-available copies of jQuery that you are welcome to link to from your pages.) In this course, we will use jQuery as a locally-hosted file; you'll find it among the demos and exercises in your class files, in the relevant directories.
We specify a set of DOM (Document Object Model) elements - in the example above, all
Usually, the starting point for our jQuery code is the ready method: we tell jQuery to execute our specified code only after the page's DOM has been loaded (so it's "ready"). The HTML elements on the page are fully loaded at this point, so we can manipulate any tag-based content. Because jQuery does not need to wait on external scripts, images, or other elements to load, this speeds up the page.
Let's look at a simple example:
We use the jQuery
ready method to run our code as soon as the DOM loads. We add a click handler for the button so that any time the button is clicked, the following occurs:
lengthof the query
$('li'), which returns all of the
<li>s on the page) and assign this value to the variable
Contentto display the length.