jQuery Basics

This section covers basic usage of jQuery from getting started to finding elements and working with CSS.

How to get started

Starting with jQuery needs three basic steps:

  1. First, download jQuery and store it in a location your web page can access. Download the latest version here.
  2. Include jQuery into your HTML page.
  3. Make use of jQuery's functionality.

A sample web page might look something like this:

<html>
<head>
<title>My first jQuery</title>
<script type="text/javascript" src="path/to/jquery.1.2.1.pack.js"></script>
<script type="text/javascript">
//this is jQuery code
$(document).ready(function () {
alert("I came from jQuery!");
});
</script>
</head>
<body>
<h2>jQuery sample</h2>
</body>
</html>

The jQuery code you decide to use depends on your needs. The rest of the How-To's on this page help to highlight what can be done. These are more simplistic examples though. Please visit the jQuery documentation or the jQuery mailing list for more details. The more advanced things you see jQuery do are usually a combination of the basics though.

A note about the different jQuery files.
jQuery tries to accomodate all types of developers. Those who want to get their hands dirty and explore jQuery's inner workings should download the uncompressed version of the jQuery library. All others probably want to use the packed version as this has the smallest footprint that is supported by all browsers. The packed version removes all extra spaces and comments to compress the library, and then encodes it to make it even smaller. The minified version of the library does the same, except it does not encode it.

How to execute code when the page loads

A common challenge of JavaScript is executing code only AFTER the referenced elements have been defined. For instance trying to find the contents of a form element will cause errors if that form element has not been rendered to the page yet. Traditional JavaScript uses the window.onload event for this (or a <body onload="initialize();"> type of call). jQuery handles this a little differently.

//assuming an initialize() function has been declared elsewhere on the page
$(document).ready( initialize );
OR
//make use of an anonymous function
$(document).ready( function () {
//initialization code goes here
});

jQuery makes a lot of use of "anonymous" or "inline" functions. In all cases a function reference can be used in their place. (a function reference is the name of a function delcared elsewhere, without the brackets, but this makes passing parameters difficult).

The samples above are roughly equivalent to the traditional onload event with a subtle difference. The onload event only fires after all page elements have completed loading. This may cause delays if you have a large image being referenced. The jQuery ready() method is fired once the DOM tree has been populated. This may happen before all page elements have been loaded. When working with jQuery, the ready() method is the preferred way of initializing a page. However there are no rules that say you cannot use an onLoad event in conjunction with jQuery.

An added bonus of the jQuery way is that you can have multiple ready() definitions. This is the case with all jQuery events. For instance:

$(document).ready(function () { alert("Number One"); });
$(document).ready(function () { alert("Number Two"); });

In this sample BOTH alerts will be fired as soon as the DOM tree is ready. These two ready() definitions could have been anywhere in our code, separtated by many lines of other code. More on this concept when we talk about jQuery events.

How to find page elements

Traditional JavaScript uses the document.getElementById() function to find a page element. This requires all elements to be referenced to have an ID set. jQuery has similar functionality, but can also find elements based on their class name, ordinal position, or a combination of these techniques.

//Reference an element by ID
$("#id");
//
//Reference an element by a CSS class
$(".classname");
//
//Reference an element by it's position
$("td:eq(2)"); //finds the third TD tag on the page (zero based)
//
//combination of these
$("#content .myclass:eq(1)");
//references the second item with a class of "myclass" inside
//the #content element

The string contained within the $() declaration is known as a selector. These selectors should look familiar to anyone who has worked with CSS - the style is the same (except the ordinal position sample). We reference IDs with the # character, and classes with the '.' (dot) character. And we can find elements contained within other elements with the same type of style as our CSS selectors - id/class of container, a space, then id/class of contained item. The basic CSS selector rules apply here.

All the samples above return an object reference to the item(s) that match the selector. Each of these matched items is wrapped into a jQuery object so that we can have common functionality between all matched items. Under the hood, jQuery supplies an array of matched items - even if it has only found one item. So using an array index can get us a reference to the raw DOM object. Consider the following:

$("p")[1];

This code will find a reference to all paragraph tags, wrap them in a jQuery object, and then we indicate we want the second element from the resulting array. This gives us the same type of object as if we had used the document.getElementById() method to find that paragraph. However, this technique is rarely needed - jQuery provides methods to access most object properties.

jQuery has other techniques for selecting elements. It provides a number of "filters" and form element references as well as the basics we've already discussed. For full details, check out the online documentation.

How to handle multiple references from a single selector

A selector may result in more than one element being referenced. For instance doing $("div") would result in a reference to ALL DIVs on the page being found. If we wanted to set the text on all the DIVs to a common value we might do something like this:

$("div").text("this is a div");

This will apply the text() method to all the elements our selector has matched. In this case, all the DIVs. This is a very handy feature, though sometimes we need to do further processing on each of the matched elements. We could set up a loop and use the underlying array of elements, but jQuery provides us with an easier way - the each() method. Let's imagine that we had 10 DIVs that contained numbers, and we need a way to calculat the sum of all those numbers. We could make use of the each() method for this.

var total = 0;
$("div.theNumbers").each( function () {
total = total + parseFloat( $(this).text() );
});
alert(total);

The magic here is the each() method. It takes a function as it's parameter and that function is executed for each of the elements matched by our selector. Additionally, the position of the element in our list is passed to the function as a parameter. If we need to make use of this position detail, then we just need to provide a parameter name (i.e. function (pos) ). For our sample problem we don't need the position so have just ignored it.

Because the function is executed for each of our matching elements, we can make use of the this keyword. Within our function, this will refer to the current DOM element. So by saying $(this), we indicate we want the jQuery object for the currently mactched item. From there we can grab the text contained in the item via the .text() method. In our sample this text should be a number, however the .text() method will return a string representation of the number to us. So we extract the numeric value via the parseFloat function (which is a native JavaScript function). The above code would work fine if we had 2 or 200,000 DIVs on the page - as long as they each had the "theNumbers" class.

How to set or get the text/html of an element

A very common task of JavaScript is to change the page contents. This can be simple text changes to existing page elements, or adding new HTML elements. jQuery provides us with two methods for this - the text() and html() methods. If we just want to set some text, we use the text() method. The value we want to set is included as a parameter to the method. The same with the html() method - except it's parameter can be a string of HTML or a reference to an HTML element.

//change the text of a target paragraph
$("#targetParagraph").text("This is new text");
//
//change the HTML of a target div
$("#targetDIV").html("<ul><li>Item One</li><li>Item 2</li></ul>");

Sometimes we want to look at the existing text or HTML of an element and use it to do further processing. Getting these values is as simple as calling the text() or html() method without any parameters. For instance, if we wanted to show an alert for these values we might do this:

alert( $("#targetParagraph").text() );
alert( $("#targetDIV").html() );

It should be noted that both the .text() and .html() methods will return strings. Even if our element only contains a numeric value, we will get a string of that nuber back (i.e. "3.14" vs 3.14). This is a problem when we do math. If math calculations are being done with these values, then we'll have to extract the numbers via the native JavaScript function of parseInt or parseFloat.

<div id="one">1</div>
<div id="two">2.5</div>
. . .
var total = $("#one").text() + $("#two".text();
alert( total );
// resuts in "12.5";
//
var total = parseFloat( $("#one").text() ) + parseFloat( $("#two").text() );
alert( total );
//results in 3.5 as expected.

How to get / set HTML tag attributes

When we are manipulating our pages, we sometimes need to get the value stored as an attribute to an HTML tag, or set an attribute to some value. This is accomplished via the .attr() method. This parameter takes two parameters - the attribute to work with, and the value to set the attribute to. Not specifying the second parameter will retrieve the current value.

//getting the ID
alert( $(".target").attr("id") );
//
//Setting the ID
$(".target").attr("id", "targetID");
//
//Changing where a form will be submitted to
$("#myform").attr("action", "otherpage.php");

The .attr() method can be used on any element. If the asked for attribute does not exist, null or undefined will be returned when requesting it's value. If setting a non-existent attribute, that attribute will be created.

If more than one attribute needs to be set then an object containing key/value properties can be used.

$("#myimg").attr({
src : "myimage.gif",
title : "My Image",
alt : "My Image",
border : 0
});

How to get and set form element values

Getting or setting the values of form elements can be a challenging chore with traditional JavaScript. We use different methods to find or set the value of a text box, radio button, or select list. jQuery provides the val() method to make this easier for us. Using val() without a parameter will get the value of any referenced form element. Giving the method a parameter will set the form element to the value indicated by the parameter.

//getting values
alert( $("input#mytextbox").val() );
alert( $("select#mylist").val() );
alert( $("input#myradio").val() );
//
//setting values
$("input#mytextbox").val("New text value");
$("select#mylist").val("ItemOne");
$("input#myradio").val(3);

How to work with radio buttons and checkboxes

Getting and setting a form element's value is not usually what we want when we have checkboxes or radio buttons. Rather, we want the value of the selected/checked item. jQuery has a selector filter to help with this called :checked. If we had 10 radio buttons, each of which had a class of "group1", we can find the selected itme with this:

$(".group1:checked").val();

Remembering that our selector can reference more than one item, and that a checkbox can have more than one item checked, we run into problems. In this case we can make use of the .each() method to build that string.

var result = "";
$(".mycheckboxes").each( function () {
result = result + $(this).val() + ", ";
});
//
alert(result);

If we need to set the value of a checkbox or radio button, then we need to a way to reference the desired item. This could be done by giving that item an ID value when creating the page, or by using one of the selector filters. If we wanted to change the fourth check box to have a value of "Item Four", we could do this:

. . .
<input type="checkbox" id="box4" name="box4" value="4">
. . .
$("#box4").val("ItemFour");
OR
$("input:eq(3)").val("ItemFour");
// Note 1: Assuming the inputs on the page are only checkboxes
// Note 2: Remember that our position is zero based

How to find the parent element

Once we have a reference to an HTML element, sometimes we need to know what element contains it. We can get this information from the DOM tree by asking for the element's parent.

var pid = $("#mytarget").parent().attr("id");

How to find an ancestor element

Occasionally we need to find an item that is containing our target element, but is further up the DOM tree than the immediate parent. Imagine we had a particular table cell, and we need to know what DIV contains the table we are in. For this we use the .parents() method. This method returns an array of all the parent elements up to to the document itself. If we need a specific item out of that list, we can pass a selector to the method.

$("#target").parents("div");

How to find a child element

We often need to find a particular element that is contained within our selected item. This is accomplished with the .children() method. This method returns an array of all the immediate children for an item. The results can be filtered by passing a selector to the method. So, imagine we had the ID for a table row, and we wanted to see the value of the table cell that had the class of "total".

$("#theRow").children("td.total");

If needing to find a child of a child, you'll need to call children multiple times, or use the .find() method.

$("#theRow").children("td").children("div.total");
OR
$("#theRow").find("td > div.total");

How to add / remove a CSS class to/from an element

Adding and removing CSS classes is a great way to highlight changes to our pages. jQuery provides the .addClass() and .removeClass() methods.

$("#target").addClass("newclass");
$("#target").removeClass("newclass");

Both methods can take multiple class names, which will be added or removed as needed.
Another method can be used to acheive similar results - the .toggleClass() method. If the class does not already exist on the element,
it is added. Otherwise it is removed.

$("#target").toggleClass("newclass");

How to change a CSS style for an element or find the current CSS value of a style

Changing the style of an element is very useful to show a reaction to a user event, or just to set up the look and feel of an element. jQuery provides the .css() method for this. The simplest form of this method is to specify a style as a parameter. With this single parameter jQuery will tell use the current value for that style. If we add a second parameter, jQuery will set the style in the first parameter to the value of the second parameter (key/value).

alert( $("#mydiv").css("font-family") );
$("#mydiv").css("font-family", "sans-serif");

This is fine when we only want to set a single value. When we want to set multiple styles we have the option of passing an object as the only parameter, with each property of the object being the style, and the property value being the value to set.

$("#mydiv").css({
"font-family" : "sans-serif",
"font-weight" : "bold",
"border" : "1px solid red"
});

How to find or set the height/width of an element.

CSS is often used to set the height and width of an element. But this height and width may be modified by our browsers when the page is rendered. A border, margin, or even padding could affect the value. Or maybe we have added an element from within JavaScript and we now want to know how much space it is taking. jQuery provides two methods for determining the rendered height and width, or setting the height / width values. These are the .height() and .width() methods. Calling these methods without a parameter retrieves the height/width in pixel units. Specifying a parameter will set the height/width to the parameter value.

var w = $("#target").width();
var h = $("#target").height();
$("#target).width(w / 2);
$("#target).height(h / 2);

If more detailed information related to height and width are needed (position, offsets, etc.), the dimensions plugin can be used.

How to check if an element exists

A common question comes up very frequently - "how do I know if XXX exists". The XXX could be a particular DIV with a class, or it might be an ID. The issue is common enough that it has been listed in the jQuery FAQs (http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_...).

Some people attempt to just check the jQuery object for the specified selector:

//This will not work
if ( $("#myid") ) {
//do something
}

This will fail. The jQuery object will ALWAYS return something. When we say $( ) we are asking for a jQuery object. So we get one back. The above code will always equate to TRUE.

The jQuery object contains a list/array of the elements that match our selector. So we can ask for the length of this internal list. The jQuery kindly exposes this length for us as the .length property. If the length is greater than zero then we have at least one object that matches our selector.

if ( $("#myid").length > 0 ) {
//do something
}

So now the only question is what we are testing. This is defined by the selector we use. If we want to know if a particular ID exists, we would use a selector of "#theID". If we were trying to determine if a DIV with a particular class existed, we would use the selector of "div.theClass".

if ( $("#theID").length > 0 ) { alert("The ID exists"); }
if ( $("div.theClass").length > 0 ) { alert("The DIV exists"); }

In this way we can check to see if ANY element exists.

How to remove content

Removing a page element is very easy, once you have a reference to it. Use the standard methods for getting the reference (jQuery selectors, etc.) then use the .remove() method.

$("#myUnWantedDIV").remove();

This code would remove the referenced element (if found), and everything within the element. Basically, that node is removed from the DOM tree.

You can get a little fancier by using the jQuery manipulation tags. For instance, to remove everything in the parent of the target element, we could do this:

$("#myUnwantedElement").parent().remove();