DRS David Soft DRS David Soft - 7 months ago 14
Javascript Question

jQuery: apply function to elements at the same time

With

jQuery.each()
, I can iterate through members of the array:

$('.example a').each(function() {
// do a lot of things here
$(this).css('color', 'red');
});




However, I need to apply a function to the jQuery array itself, and not to its members. So I wrote a little plugin to do this:

$.fn.all = function( callback ) { return callback.call( this ); }

$('.example a').all(function() {
// do a lot of things here
$(this).css('color', 'red');
});




I'm sure that jQuery should have an elegant way to do this, but I haven't found anything in the documentation, or by Googling.

Is it possible, and if it is, how do I achieve this without using custom plugins?

UPDATE: I can not do
$('.example a').css('color', 'red');
directly. I have a dozens of calculations in the function, so I have to use something similar to the plugin I wrote.
I am asking for a callback. The correct answer must provide a callback similar to the custom function.

Answer

You don't need a plugin, you can use call directly:

(function() {
  // do a lot of things here
  this.css('color', 'red');
}).call($('.example a'));

Or consider passing the array-like object as an argument

(function(arrayLike) {
  // do a lot of things here
  arrayLike.css('color', 'red');
})($('.example a'));

Or if you prefer a jQuery way

$.each([$('.example a')], function(){
  // do a lot of things here
  this.css('color', 'red');
});