g(..).forEach(callbackFn, [thisObject])

Iterates through all elements in the Gimme Object's underlying array, executing the specified callback on each DOM element. The callback automatically receives a direct reference to the DOM element, the index of that DOM element, and a reference to the underlying array being iterated over. Optionally, you may specify the object to be used as the "this" object in the callback by supplying the second parameter.

Returns: Itself (the same Gimme Object is returned so additional methods can be chained together seamlessly).
Params:
  • callbackFn, required: A function reference that will be invoked for each element in the Gimme Object's internal array.
  • thisObject, optional: An object to be used as the "this" object from within the callbackFn.

Examples:
// set the .innerHTML of all <p> elements to "I am paragraph #." (which # is the number paragraph in the page)
g('p').forEach(function(elem, idx, arr)
{
	elem.innerHTML = 'I am a paragraph ' + idx;		// notice that this is direct access to the DOM elem -- not a Gimme object
});


// Gimme can also be used to iterate over any standard array
var myArray = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ];
g(myArray).forEach(function(elem, idx, arr)
{
	// advance each character by 1
	arr[idx] = String.fromCharCode(arr[idx].charCodeAt() + 1);
});
alert(myArray);				// [ 'B', 'C', 'D', 'E', 'F', G', 'H' ]


// Example which specifies the "this" object
var thisObject = { firstName: 'Stephen', lastName: 'Stchur' };
var allDivs = g('div');
allDivs.forEach(writeName, thisObject);

function writeName(elem, idx, arr)
{
	elem.innerHTML = 'First Name: ' + thisObject.firstName + ', Last Name: ' + thisObject.lastName;
}




Related Information:
  • The DOM element, elem, the loop index, idx, and the array reference, arr, are all automatically passed into the callbackFn.
  • Inside the callbackFn, the "this" is whatever object you passed into the .forEach(..) function as the 2nd parameter. If this parameter was omitted, then "this" will refer to the window object.

Last edited Nov 13, 2007 at 9:27 PM by sstchur, version 2

Comments

No comments yet.