<%response.buffer=true%> <% yere = year(date()) Response.Expires = 0 %> Advanced Forms
<jQuery Fundamentals >
  spacerspacer

JQuery Intro

jQuery is a lightweight JavaScript library that takes the burden of browser differences away when manipulating the DOM. It was released in January 2006 at BarCamp NYC by John Resig.

Why jQuery?: Good question! jQuery is emerging as one of the most popular JavaScript APIs but it is by no means the only one. You can make equally good use of MooTools, Scriptaculous and the Yahoo UI. Lately jQuery has been emerging as the most popular and clients and employers are beginning to demand it, so this is where we'll place our focus.

DOM Alternative: JQuery provides a shorthand method for cross browser DOM manipulation. Instead of building forked code to deal with browser differences we can shift the heavy lifting to an API and can more work with less lines of code.

Help With Events: Not only will jQuery help us with DOM manipulation, it will also help us with browser differences and complexities regarding assigning (and unassigning) event handling code to events.

Plugins and Effects: Besides helping us keep browser differences from becoming an issue, jQuery provides specialized plugins built both by the jQuery development team and by third parties. There are several special effects built into the jQuery core that allow elements to fade in and out of view and slide up and down. Finally there is an entire suite of customizable user interface tools that we allow us to identify a style and download a customized package to use with our sites.

jQuery Objects: jQuery creates its own objects which have jQuery specific properties and methods. It's these properties and methods that allow us to manipulate elements quickly. On occasion we may wish to do traditional DOM manipulation on an element (or array of elements) selected via jQuery. We can do this with the jQuery get() method.

JQuery Latest: When we work with jQuery, we can either download the API, or merely reference it as a JS include file in our pages:

<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>

window.onload, the jQuery way: We're familiar with using the onload attribute of the body tag to load JS scripts and the unobtrusive equivalent window.onload event. Now that we're about to do jQuery, there is a new way to attach code to the window.onload event:

$("document").ready()

Inside the parens above we can add an anonymous function that will fire off after the page loads:

$("document").ready(function(){

//do clever jQuery here

});

Using jQuery also adds the benefit of being able to add more than one function to the event like our addOnload() custom function. We can call the $("document").ready() method as often as we need, and each time more instructions are added to the window.onload event.

$("document").ready() is so commonly used that we'll even see a shortcut to assigning an anonymous function to it thus:

$(function(){

//$("document").ready(), the shortcut!

});

The above is the short-cut equivalent of the first version of the jQuery window.onload event handler.

Basic Selectors: jQuery makes short work of selecting DOM elements. View the jQuery version of selectors from some of our favorite DOM methods:

Selector Purpose Example Returns
element name
Selects all elements of a certain type
$("p")
Selects all <p> tags, like getElementsByTagName()
id
Selects a single element by the id attribute
$("#myDiv")
Selects a single element - like getElementById()
class
Selects all elements which have a specific class attribute
$(".myClass")
Selects all elements that have a class attribute of myClass - like getElementsByClassName()

Combination Selectors: Besides the shorthand versions of traditional DOM selectors, jQuery allows you to combine selectors to further specify a set of elements. Here is a list of some advanced combination selectors:

Combination Selector Purpose Example Returns
selector,selector,selector
Selects a comma separated list of different selectors
$("a,#myID,.myClass")
All <a> tags, an element with an ID of myID and all elements with a class of .myClass
.myClass.myOtherClass
Selects only elements which have both classes
$(".myClass.myOtherClass")
Both classes must be applied which filters down the list of selectors
parent>child
Selects all direct child nodes of the parent selector
$("#myID>p")
Selects all <p> tags that are directly inside an element with an id of myID (can't be nested)
ancestor descendant
Finds all descendant elements inside an container element
$("ul li.myClass")
Selects all <li> tags with a class of myClass inside any <ul> tag (nested or not)
prev + next
Selects all next elements that are next to a prev element
$("p + b")
Selects all <b> tags next to a <p> tag
prev ~ siblings
Selects all sibling elements that come after prev and match the siblings selector
$("#myID ~ span") Selects all <span> tags that come after an element with an id of myID

Basic Filters: Filters provide a way to narrow down the selectors chosen to match certain conditions. For example we could select all <p> tags, then filter down our list to only the first <p> tag of a set. Here is a list of some basic filters:

Filter Purpose Example Returns
:first
Selects only the first instance of the set
$("p:first")
The first <p> tag in a set
:last
Selects only the last instance of the set
$(".myClass:last")
The last element with a class of myClass in a set
:even
Selects only even numbered items in the set
$("p:even")
Selects all <p> tags that are even numbered (0,2,4, etc.)
:odd
Selects only odd numbered items in the set
$(".myClass:odd")
Selects all odd elements (1,3,5, etc.) of a set of elements with a class of myClass
:eq(n)
Equal: Returns only the item at the given index
$("p:eq(2)")
Selects only the <p> tag in the #2 position
:gt(n)
Greater Than: Includes elements that are past (greater than) the given index
$("p:gt(1)") Selects all <p> tags greater than the first <p> tag in a set (1 or higher)
:lt(n)
Less Than: Includes elements that are before (less than) the given index
$("p:lt(5)") Selects all <p> tags that come before the #5 tag in the set (4 or lower)
:header All <h> type elements $(".myClass:header") Selects all <h1>, <h2>, etc. header elements that have myClass applied
:animated()
All elements currently being animated
$("p:animated()") Selects all currently animated <p> elements
:not(selector)
Negation: Elements that do not match the given selector
$("p:not(eq(3))") Selects all the <p> tags not in the #3 position

jQuery Selector Test Bed: Our book provides probably the best introduction to jQuery I've seen thus far. To get a better feel for selectors, view our books jQuery Selector Test Bed

Attribute Filters: We can also filter our set of elements returned by investigating the contents of the attributes inside the elements (beside the class and id attributes, addressed above). We can further filter by identifying partial text matches, etc:

Attribute Filter Purpose Example Returns
[attribute]
Contains Attribute: Selects elements that contain the given attribute, regardless of content
$("a[href]")
All <a> tags that have an href attribute (no anchors)
[attribute=value]
Matching Value: Selects elements that contain the given attribute only if it has a matching value
$("p[class=Current]")
All <p> tags that have the class attribute equal to Current
[attribute!=value]
Attribute Exists, Value Does Not Match: Selects elements that contain the given attribute but must not match the given value
$("p[class!=Current]")
All <p> tags that have the class attribute not equal to Current
[attribute^=value]
Starts with: Selects elements that contain the given attribute only if they start with a given string
$("div[id^=myDiv]")
Selects all <div> elements whose id attributes start with "myDiv", for example, myDiv1 and myDiv2
[attribute$=value]
Ends With: Selects elements that contain the given attribute only if they end with a given string
$("p[class$=ing]")
Selects all elements have a class attribute ending with "ing", for example "raining" and "pouring"
[attribute*=value]
Contains: Selects elements that contain the given attribute only if they contain a given string somewhere inside
$("div[id*=iv]")

Selects all <div> elements whose id attributes contain the letters "iv" for example, myDiv and yourDiv

Compare to our use of indexOf() to find a needle

[attr1][attr2]
Must match all specified attribute filters
$("img[class=pics][src*=sky]") Selects all <img> tags that have a class of pics attached and the src attribute includes the string 'sky', for example 'blue-sky.jpg' and 'red-sky.jpg'

Content, Visibility & Child Filters: We can also filter our set of elements based on their current content, or whether or not jQuery currently has the visibility of the element set to visible or hidden:

Special Filter Purpose Example Returns
:contains(text)
Selects only elements that contain the text
$("p:contains(important)")
All <p> tags that contain the text "important"
:empty
Selects only empty elements
$("p:empty")
Selects all <p> tags that contain no content
:has(selector)
Elements must contain at least one element that has the selector
$("ul:has(li[class=myClass])")
All <ul> tags that contain <li> elements with class attribute of myClass
:parent

Matches all elements that are parents - (must have one child element, even text)

$("p:parent")
Selects all <p> tags that contain content
:visible
Only visible elements
$("p:visible")
Selects all <p> tags that are visible
:hidden
Only hidden elements
$("p:hidden")

Selects all <p> tags that are hidden

:nth-child()
Matches index, even or odd increments. Also allows an equation to be entered.
$("ul li:nth-child(2)")

Selects the 2nd child <li> items in all <ul> elements (starts count at one instead of zero

:first-child
Matches elements that are the first child of their parent
$("ul:first-child")

Selects all elements that are the first child of each <ul> tag

:last-child
Matches elements that are the last child of their parent
$("ul:last-child")

Selects all elements that are the last child of each <ul> tag

:only-child
Matches elements that are the only child of their parent
$("ul:only-child")

Selects all elements that are the only child of each <ul> tag

Document Traversal: jQuery provides a set of methods and properties for navigating or manipulating the returned result set of elements. We can determine the number of elements returned with the length property or loop through each element with the each() method:

var counter = 1;
$("p").each(function(){
        $(this).prepend(counter+ "). ");
        counter++;
});

In the above each <p> tag is prepended with a number that increments, simulating an ordered list with paragraphs:

1). para1

2). para2

Note the reference to $(this) which allows us to access the individual <p> tag in the loop.

Here are some core Document Traversal Methods & Properties:

Traversal Method/Property Purpose Example Returns
.size(), .length
The number of elements in a jQuery result set

$("p").length

$("p").size()

The number of <p> tags on the page
.get()
Returns an array of DOM elements from a jQuery result set. Use this for straight DOM manipulation.
$("p").get()
Returns all <p> tags for normal DOM manipulation
.get(n)
Returns a single element as a DOM element from a jQuery result set. Use this for straight DOM manipulation.
$("p").get(0)
Returns the first <p> tag for normal DOM manipulation
.find(expression)

Searches for descendant elements that match an expression

$("ul").find("li.myClass")
Selects all <li> tags within <ul> tags that have a class named myClass
.next()
Selects the tag immediately following the current tag
$("#myDiv").next()
Returns the tag immediately following the myDiv element (the next sibling)
.each(function)
Execute a function for each matched element
$("p").each(init)
Run the init function on each of the returned <p> tags

Statement Chaining: In jQuery we can string together (chain) multiple methods or operations without needing to return our method to a variable. View the following:

$("ul li:even").css("background-color","blue").hide(); //color only even numbered <li>s, then hide them

Content Methods: jQuery provides a set of methods to manipulate the content in and around the elements. One such method is html(), which is read/write capable. In this regard, and in operation the .html() method is almost the exact equivalent to the DOM's innerHTML() method. Here's how to see inside the contents of an element:

alert($(#myDiv.html());

In the above code we use the html() method in read mode, and merely output the contents to an alert(). Here's how we insert (and replace) any HTML inside the element:

$('#myDiv').html("Here's some new HTML! <b>this is bold!<b>");

We can also create a new jQuery element and add that data to another element:

var newHTML = $("Here's some new HTML!");
$('#myDiv').html(newHTML);

Note the variable newHTML looks like a standard JS variable. However it is a full fledged jQuery object, in which all of the jQuery methods and properties will apply.

Here's an overview of some key content manipulation methods:

Content Method Purpose Example Returns
.text(text)
Inserts text into an element, but does not convert tags

$('#myDiv').text("<b>this is not bold<b>");

Inserts text to a div with an id of myDiv, but no HTML is converted (ala DOM)
.html(html)
Extracts HTML from or inserts html into an element

$('#myDiv').text("<b>this is bold<b>");

Inserts text into to a div with an id of myDiv, and converts HTML (ala innerHTML)
.append(html)
Adds html into the element, but after the current contents
$('#myDiv').text("this is added after");
Text is added immediately after existing text in the myDiv element
.prepend(html)
Adds text into the element, but before the current contents
$('#myDiv').text("this is added before");
Text is added immediately before existing text in the myDiv element
.after(html)
Inserts HTML immediately after the existing element
$("p").after("<p>Para after</p>")
Adds new <p> tag after the selector
.before(html)
Execute a function for each matched element
$("p").before("<p>Para Before </p>")
Adds new <p> tag before the selector
.insertAfter(selector)
Inserts all elements after the current selection

myImg = $('<img src="icon.jpg">');

$(".myClass").insertAfter(myImg)

Inserts myImg after each element with a class of myClass
.insertBefore(selector)
Inserts all elements before the current selection

myImg = $('<img src="icon.jpg">');

$(".myClass").insertBefore(myImg)

Inserts myImg before each element with a class of myClass
.remove()
Remove (destroy) the selected elements
$(".myClass").remove()
Removes (destroys) all elements with a class of myClass
.empty()
Remove (destroy) all child elements in the selection
$(".myUL").empty()
Removes (destroys) all child elements of a class named myUL (implied destruction of <li> elements)
.replace(html)
Replace all selected elements with this html
$("#myDiv").replace("<div>new Div!</div> ")
Replaces entire existing element(s) with new HTML
.wrap(html)
Wraps each selected element in our HTML element (no closing tag)
$(".myLink").wrap('<div style="border:1">')
Wraps each element with a myLinks class in a div with a border of 1px
.wrapAll(html)
Replace all selected elements with this html
$(".myLink").wrapAll('<div style="border:1">')
Wraps all selected elements with a myLinks class in a div with a border of 1px
.clone()
Copies all matched elements and event handlers and selects the clones
var aLinks = $("a[href]")
Clones a copy of all page links that have an href attribute (avoids anchors)

jQuery Content Functions Test Bed: Our book provides a jQuery Content Functions Test Bed

Content Manipulation & Retrieval Example: To see many of the methods above used, view Joe Marini's automatic table of contents

JS Template version 4: We have a fourth version of our JS Template, this one designed to help with jQuery projects. View the following file from the package that displays a few jQuery effects wired via compound selectors: jq_template6.htm

Here's the zip file: JS Template 4 Zip File

Next: In the next lesson, Applied JQuery, we'll learn how to attach functions to events and see what else jQuery can do!

   
Print this Page Back To Top

2000- <%=yere%> newMANIC INC, All rights reserved