Chapter 5. Arrays and Iteration

In this chapter, I talk about the methods that jQuery provides that help you work with arrays. Historically, working with arrays in JavaScript often required you to come up with your own helper methods and to deal with writing tedious redundant code every time you wanted to enumerate over the contents of an array.

As you saw in Chapter 4, jQuery provides a rich, robust, and helpful API for various tasks associated with manipulating the content in a document. In this chapter, you see that jQuery also does not leave much to be desired in what it offers for dealing with arrays.

Basic Iteration

In this section, you learn a whole new way to approach the task of iterating over an array of values using jQuery's $.each() method. Up to now, when it comes to looking at each individual value contained within an array, you're probably used to dealing with a loop that looks something like this:

var $items = document.getElementsByTagName('div');

for (var $i = 0; $i < $items.length; $i++) {
  // Do something with each item
  alert($item[$i].innerHTML);
}

You have an array of items, or a static node list, or a live node list. Then you make a for loop, you define a counter, and you proceed to iterate over the contents of your array or list.

jQuery makes this completely unnecessary, by providing a way to iterate over an array or list using a function call instead of a for loop, and a callback function that's used to actually look at each individual item. The function that jQuery ...

Get Beginning JavaScript® and CSS Development with jQuery 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.