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.
- Printer-friendly version
- Login or register to post comments
