O'Reilly logo

Beginning JavaScript® and CSS Development with jQuery by Richard York

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

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