How to Jquery each complete

38,676

Solution 1

To execute code after the each loop is over :

var count = $("element").length;

$("element").each(function (i) {
    // loop
    if (i+1 === count) {
        // this will be executed at the end of the loop
    }
});

Solution 2

The promise() method is usually for AJAX, but it can be used with each() to achieve what you want:

$('.element').each(function (key, val) {
    console.log('Do something to each individual .element');
}).promise().done(function () { 
    console.log('Did things to every .element, all done.');
});

Solution 3

You can simply use:

$.when( $.each() ).then(myFunc, failFunc);

Solution 4

Simply check the index of the element, i, with the number of element at the end of the .each() loop. If it matches, then you are done with looping:

$('element').each(function (i, v) {
    // Do all the stuff here

    // Check if you are at the last item
    if ($('element').length === i+1) {
        // Code to execute when you are at the last item
    }
});
Share:
38,676
Baha Adıyaman
Author by

Baha Adıyaman

Updated on July 18, 2022

Comments

  • Baha Adıyaman
    Baha Adıyaman almost 2 years

    I did not do the complete in $.each(). How this is done? Please help me.

    $("element").each(function (i, v) {
            //No problem
        }, function () {
            //How to complete finished ??
            // alert(each finish);
        })
    
  • Brewal
    Brewal over 9 years
    putting it after the each will means the code will be executed even if there's no elements (and therefore no looping)
  • Spokey
    Spokey over 9 years
    @Brewal OP wants a callback for when .each finished.
  • Brewal
    Brewal over 9 years
    @Spokey I think I understood that
  • Bill Criswell
    Bill Criswell over 9 years
    A callback would run when something is done, not if it's actually done something... if that makes sense.
  • Brewal
    Brewal over 9 years
    Lol, ok I see what you guys are talking about, but yeah... It is hard to make sens when talking about callback on synchronous code ^^
  • TheAmazingKnight
    TheAmazingKnight about 8 years
    this doesn't work with $.each(). Error: Uncaught TypeError: $.each(...).promise is not a function.
  • Manos
    Manos almost 8 years
    it doesn't work, because it wasn't supposed to :) if you want something to happen after $.each completes, just type right after it. $.each runs synchronously
  • vaso123
    vaso123 over 7 years
    @Manos But it's not ok, if you calling asynch scripts inside of each.
  • Rob S.
    Rob S. over 6 years
    $.each() and element.each() are two different functions... api.jquery.com/jquery.each vs api.jquery.com/each