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

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