Installing jQuery Library
For jQuery code to work you need to install the jQuery library in the head of your web page document, WordPress and other CMS’es already come with it pre-installed so make sure not to double up.
Get the latest jQuery here. There are 2 versions, the v2 version has no support for IE 6, 7, 8 whilst v1 version does. Use the one more suitable version to your target browser audience.
Download the production version and reference it in the head of your document.
<script src="/js/jquery-1.11.1.min.js"></script>
When does jQuery execute?
jQuery uses the document.ready
event to execute or fire it’s code, document.ready
is available once the DOM of the page has loaded which is before the actual contents of the page are loaded.
You can use multiple occurrences of this event which jQuery will run in succession. This approach is favourable to the traditional window.onload
event which only executes once all the page content has downloaded.
document.ready
The document.ready event is written out like so…
$("document").ready(function() { //code goes here });
Selecting HTML elements on the page
If you are familiar with CSS, then jQuery selection techniques should seem familiar.
Selecting a HTML tag element, for example all the <p> tags on the page:
$("document").ready(function() { $("p"); });
Selecting based on a CSS class or ID would be:
$("document").ready(function() { $(".classname"); });
Selecting based on HTML Tag and classname or ID:
$("document").ready(function() { $("p.classname"); });
Selecting multiple elements require the elements to be comma separated:
$("document").ready(function() { $("ul,p"); });
Select descending elements is with one element following another; parent child:
$("document").ready(function() { $("ul li"); });
Select adjacent element is with a ‘+’:
$("document").ready(function() { $("ul+p"); });
Select direct child elements of parent element is with a greater than sign:
$("document").ready(function() { $("ul > li"); });
Select like elements that come after another element:
$("document").ready(function() { $("ul ~ p"); });
Part 2 will deal with Filtering HTML elements with jQuery.