Exploring jQuery Selectors, Part 1
jQuery is a widely popular cross-browser JavaScript library that simplifies the client-side scripting of web applications. jQuery achieves this simplicity in part by offering selectors that match elements from the current HTML document's Document Object Model (DOM) tree.
This article launches a three-part series that introduces jQuery's selectors. Part 1 defines this feature, presents some generic syntax for working with selectors, and takes you on a tour of jQuery's basic and hierarchy selectors. Later articles in the series cover more selector categories.
What Are Selectors?
A selector is a string-based expression that identifies a set of DOM elements. For a given selector, jQuery searches the current document's DOM tree for all matching elements. This search typically begins with the root element, unless a context is specified to narrow the search.
The selector is typically passed as the first or only argument to the jQuery(selector [, context]) constructor. The optional second argument lets you narrow the search context. For example, you might want to restrict the search to the context of a clicked element.
You can specify a selector by adhering to the jQuery(selector [, context]) syntax, or you can use the more convenient $(selector [, context]) alias syntax. Both syntaxes are demonstrated by the following expressions:
jQuery("*") $("*") jQuery('div.mydiv').click(function() { alert($('span', this).text()); });
The first two expressions select all elements starting from the document's root element. The third expression selects (starting from the root element) all <div> elements whose class attribute is set to mydiv. Each expression returns a jQuery object containing the selected elements.
The third expression attaches, via jQuery's click() method, a click event handler to each selected <div> element. When the element is clicked, the anonymous function passed to click() is executed.
The anonymous function first executes $('span', this).text(), which invokes jQuery's text() method to return the combined text of all selected <span> elements within the clicked element. This text is subsequently displayed to the user via alert().
The jQuery object's ".length" property returns the number of elements (which might be zero) that match the selector. For example, $('span', this).length returns the number of <span> elements within the clicked <div> element.
After obtaining a jQuery object, you can invoke a method on this object that applies to each selected element; for example, text(). A second example is css(propertyName, value), which modifies the specified property of each supportive element, as follows:
$('*').css("color", "#00f");
This expression sets the value of the color property to blue for each selected element that supports this property.