5

I have this code:

i = 60;
i = $(this).find('li a').each(function(i) {
    w = $(this).text();
    $('#js').text(w);
    w = $('#js').width();
    if(w > i) {
        i = w;
    }
    return i;
});

It's wrong :-). I have X strings ($(this).find('li a')). I want to get the length (px) of the longest one and save its length to variable i that I will use later in my code.

1 Answer 1

14

Don't declare an i argument on the function you're giving each, don't return anything from the each function, and don't assign the result of each to i. Then it should work.

i = 60;
$(this).find('li a').each(function() {
    var w = $(this).text();
    $('#js').text(w);
    w = $('#js').width();
    if(w > i) {
        i = w;
    }
});

That way, the function you're passing into each is a closure over i and so can access and update it directly. By declaring i as an argument of the each callback, you were dealing with a different i on each iteration (the one that jQuery passes in, which is the index of the element in the set). And separately, the return value of each is the jQuery object on which you call it (docs), which clearly isn't what you want.

More about closures, if you're not clear on them: Closures are not complicated

In the code above, I also declared the w variable as local to the each callback, because I'm assuming you don't have a w variable outside of it you want updated and so were falling prey to The Horror of Implicit Globals.

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

4 Comments

Also I think the return i; doesn't make much sense.
@mridkash: You're right, I did that in the code I posted but forgot to mention it in the opening sentence.
+1 for pointing out that a baby penguin dies whenever the var keyword is omitted.
Also, returning false from the function stops the each, returning anything else is the equivalent of "continue."

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.