0

As the title, is there a way to pass an element into a function without using an anonymous function?

Or in other words:

I know I can pass element into function as follows:

function fakeFunction(elementReceived){
    elementReceived.hide();
}
$(".class-x").each(function(){
    fakeFunction($(this));
});

which is not acceptable as I am required to prevent using anonymous function due to some problem in testing.

So I write something like this:

function fakeFunction(){
    $(this).hide();
}
$(".class-x").each(fakeFunction);

This is better but the readability is decreased, as the function in the actual code is very far away from the calling line and using $(this) directly is confusing.

I was told (and was requested to investigate) that something like the following should be possible:

function fakeFunction(elementReceived){
    elementReceived.hide();
}
$(".class-x").each(fakeFunction, $(this));

but the $(this) in the above code passed the whole document instead..... What should be the proper way to write it?

3
  • 1
    If the testing process leads you to add hacks to avoid perfectly valid (and recommended) patterns with jQuery, I would suggest to also review the testing process ... Commented Oct 28, 2013 at 8:06
  • While your suggestion is good, it is not something that can be easily done in a short period of time. Changing my code will be a better option at this moment. Commented Oct 28, 2013 at 8:21
  • I know. Just voicing it. Commented Oct 28, 2013 at 8:29

1 Answer 1

3

If you look at the documentation for each, you'll see that the second argument to the function is the element (e.g., the same as this). So:

function fakeFunction(index, element){
    $(element).hide();
}
$(".class-x").each(fakeFunction);

(Of course, in this particular case, you could just do $(".class-x").hide();, but I assume fakeFunction actually does something else.)

Sign up to request clarification or add additional context in comments.

2 Comments

While this improves readability and solve my problem..... Is there really no way to pass element directly? That second argument is actually string and still require $(element).hide(); instead of element.hide(); (but at this point, it is just my curiosity instead of a problem now)
@user1273587: The second argument isn't a string, it's a DOM element. You just use $() to wrap it in a jQuery instance to get access to the jQuery stuff. You could (for instance) do element.style.display = "none"; to hide it without using jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.