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 3. Beyond the Basics

Ralph Whitbeck

Introduction

jQuery is a very lightweight library that is capable of helping you do the simple selections of DOM elements on your page. You saw these simple uses in Chapter 1. In this chapter, we’ll explore how jQuery can be used to manipulate, traverse, and extend jQuery to infinite possibilities. As lightweight as jQuery is, it was built to be robust and expandable.

3.1. Looping Through a Set of Selected Results

Problem

You need to create a list from your selected set of DOM elements, but performing any action on the selected set is done on the set as a whole. To be able to create a list with each individual element, you’ll need to perform a separate action on each element of the selected set.

Solution

Let’s say you wanted to make a list of every link within a certain DOM element (perhaps it’s a site with a lot of user-provided content, and you wanted to quickly glance at the submitted links being provided by users). We would first create our jQuery selection, $("div#post a[href]"), which will select all links with an href attribute within the <div> with the id of post. Then we want to loop through each matched element and append it to an array. See the following code example:

var urls = [];
 $("div#post a[href]").each(function(i) {
    urls[i] = $(this).attr('href');
});

alert(urls.join(","));

We were able to make an array because we iterated through each element in the jQuery object by using the $().each(); method. We are able to access the individual ...

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