Skip to Main Content
jQuery Cookbook
book

jQuery Cookbook

by Cody Lindley
November 2009
Intermediate to advanced content levelIntermediate to advanced
480 pages
11h 50m
English
O'Reilly Media, Inc.
Content preview from jQuery Cookbook

Chapter 2. Selecting Elements with jQuery

James Padolsey

Introduction

At the very core of jQuery is its selector engine, allowing you to select elements within any document based on names, attributes, states, and more. Because of CSS’s popularity, it made sense to adopt its selector syntax to make it simple to select elements in jQuery. As well as supporting most of the selectors specified in the CSS 1–3 specifications, jQuery adds quite a few custom selectors that can be used to select elements based on special states and characteristics. Additionally, you can create your own custom selectors! This chapter discusses some of the more common problems encountered while selecting elements with jQuery.

Before the first recipe, let’s discuss a few basic principles.

The easiest way to target a specific element or a set of elements within a document is by using a CSS selector within the jQuery wrapper function, like so:

jQuery('#content p a');
    // Select all anchor elements within all paragraph elements within #content

Now that we’ve selected the elements we’re after, we can run any of jQuery’s methods on that collection. For example, adding a class of selected to all links is as simple as:

jQuery('#content p a').addClass('selected');

jQuery offers many DOM traversal methods to aid in the element selection process, such as next(), prev(), and parent(). These and other methods accept a selector expression as their only parameter, which filters the returned results accordingly. So, you can use CSS ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

jQuery UI in Action

jQuery UI in Action

TJ VanToll
Head First jQuery

Head First jQuery

Ryan Benedetti, Ronan Cranley

Publisher Resources

ISBN: 9780596806941Supplemental ContentErrata Page