For the sake of demonstration, assume your goal is actually to get the id attribute value for
each element on the page. You could write three separate jQuery statements accessing each
element's id attribute value. If we were to do that, it might look something like this:
$('#div1').attr('id');
$('#div2').attr('id');
$('#div3').attr('id');
// or
var $divs = $('div'); // Cached query.
$divs.eq(0).attr('id'); // Start with 0 instead of 1.
$divs.eq(1).attr('id');
$divs.eq(2).attr('id');
That seems a bit verbose, no? Wouldn't it be nice if we could loop over the wrapper set and
simply extract the id attribute value from each of the
elements? By using the
$().each() method, we invoke another round of iteration when our wrapper set requires
explicit iteration to handle multiple elements.
In the code example below, I use the $().each() method to loop over the wrapper set, access
each element in the set, and then extract its id attribute value.
Sample: sample18.html