Explain jQuery Selectors

Selectors are the strings you pass to the jQuery function to select elements in the DOM. Example:

$(function () {
	$("#album-list img").mouseover(function () {
	$(this).animate({ height: '+=25', width: '+=25' })
		.animate({ height: '-=25', width: '-=25' });
	});
});

In this example, we used “#album-list img” as a selector to find image tags. If you think the string looks like something you might use in a cascading style sheet (CSS), you would be correct. The jQuery selector syntax derives from CSS 3.0 selectors, with some additions. Table 8-1 lists some of the selectors you’ll see in everyday jQuery code.
Here are some examples of Common Selectors:

Example Meaning
$(“#header”) Find the element with an id of “header”
$(“.editor-label”) Find all elements with a class name of “.editor-label”
$(“div”) Find all elements
$(“#header div”) Find all elements that are descendants of the element with an id of “header”
$(“#header > div”) Find all elements that are children of the element with an id of “header”
$(“a:even”) Find evenly numbered anchor tags

The last line in the table demonstrates how jQuery supports the same pseudo-classes you might be familiar with from CSS. Using a pseudo-class allows you to select even or odd numbered elements, visited links, and more. For a full list of available CSS selectors, visit http://www.w3.org/TR/css3-selectors/.

Tagged , . Bookmark the permalink.

Leave a Reply