Reputation: 85
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
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