3.1. Looping Through a Set of Selected Results by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 elements and execute jQuery methods against those elements because we wrapped the this variable in a jQuery wrapper, $(), thus making it a jQuery object.

Discussion

jQuery provides a core method that you can use to loop through your set of selected DOM elements. $().each() is jQuery’s for loop, which will loop through and provide a separate function scope for each element in the set. $().each(); will iterate ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required