cursedphil
cursedphil

Reputation: 85

Pass $(this) to callback of each() in jQuery

I have a function that I call by calling each() on an element in jQuery. I want to pass the element that I called each() on as an argument. This is an abstracted version of the code that I have now, but when I pass $(this) to the callback of each(), it passes the document instead.

var myFunction = function(element){
    //do stuff with element
};

$('.element').each(myFunction($(this)));

I'd be happy for any help, cheers!

Upvotes: 0

Views: 218

Answers (2)

Pointy
Pointy

Reputation: 413682

The pattern you're working on is something that can be directly converted to a jQuery add-on:

$.fn.myFunction = function() {
  return this.each(function() {
    // original "myFunction" code
    // here, "this" will be bound to each element
  });
};

Now you can write

$(".element").myFunction();

If you write it with that return statement as in my example, you can use it just like any other jQuery function:

$(".element").addClass("something-else").myFunction().hide();

Upvotes: 0

void
void

Reputation: 36703

$('.element').each(function(){
    myFunction($(this)); 
});

Upvotes: 3

Related Questions