Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to use each starting at an index other than 0

Tags:

jquery

each

I have a collection of elements that I want to loop over using each, but I am looping over them inside an outer for loop. When I find what I want in the each, I return false to break out. The next time the outer loop runs, I want to start in the each at the element after the one I returned at. A generic code example:

var nextIndex = 0;

for (var j=1; j <= someCount; j++) {
    // do outside loop stuff

    $('#someElemID').find('.someClass').each(function(index) {
        if (/*this is right one*/) {
            // do something
            // next index should get passed to each function next loop... somehow?
            nextIndex = index + 1; 
            return false;
        }
    });
}

I thought about switching to a for loop, but then I got confused as to how to access the return from the .find('.someClass'). Maybe that's a separate question itself...

Is this an obvious one?

like image 691
Carvell Fenton Avatar asked Jan 21 '11 15:01

Carvell Fenton


People also ask

How to break each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

How to use each function for array in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How use each in jQuery?

each() jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.

How to loop through array in jQuery?

Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.


1 Answers

Use slice() http://api.jquery.com/slice/

$('#someElemID').find('.someClass').slice(nextIndex).each( ...  

btw if the elements are static, consider caching:

var $elms = $('.someClass', '#someElemID'),
    nextIndex = 0;

for (var j = 1; j <= someCount; j++) {
    // do outside loop stuff

    $elms.slice(nextIndex).each(function(index) {
        if (/*this is right one*/) {
            nextIndex = index + 1; 
            return false;
        }
    });
}

That should improve performance considerably.

like image 172
Šime Vidas Avatar answered Oct 11 '22 17:10

Šime Vidas