tags:

views:

61

answers:

3

How can I exit from $.each loop when a condition is met? I don't want to iterate the collection further.

$(vehicles).each(function() {
    if (this["@id"] === vehicleId[0]) {
      vehicle = this;
    }
});

I tried with break; & return; statement but it looks the execution doesn't not stop at that point. Any idea would be greatly appreciated.

+3  A: 

Returning false is the equivalent of breaking out of a $.each loop. So in your example:

   if (this["@id"] === vehicleId[0]) { vehicle = this; return false; }
Joey C.
+2  A: 

You need to explicitly

return false;

http://api.jquery.com/each/

Evan Trimboli
A: 

Since .each() iterates over a wrapped set and executes the given function on each element, break won't affect the actual iteration. However, you can achieve what you're after without iteration by simply calling

vehicle = $('#' + vehicleId[0], $(vehicles));

or (as suggested by Kobi in a comment)

vehicle = $(vehicle).filter('#' + vehicleId[0]);
Tomas Lycken
That'd be `$(vehicles).filter('#id')`, iirc, you cannot filter a collection that way.
Kobi
@Kobi, Actually, both work. Your version is arguably better (at least it's a lot clearer what is actually being done) but mine should work too. If `vehicleId[0]` has a value of, say, "id", my line of code will look for `'#id'` in the context of `$(vehicles)`, which is exactly what your line does too. =)
Tomas Lycken