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

Get jQuery Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.