O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required