Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use .each for div if I use .append in AJAX?

I send AJAX and get HTML with many div element (.card), I use .append for add new .card elements after each AJAX request (like a infinity scroll). How can I use .each for all .card on page after one, two, three ...etc AJAX requests?

$( document ).ready(function() {
$('.card').each(function(i) {
   addMarker(i);
}
});

and

$( document ).ajaxComplete(function() {
$('.card').each(function(i) {
   addMarker(i);
}
});

not working.

I get count from zero on new .card divs every AJAX request.


1 Answers

If you have a container <div class="container"></div> where you are appending the cards <div class="card"></div> then you should use the following script:

$(document).scroll(function(){
    $.ajax({
        method: "GET",
        url: "file.php",
        success: function(data){
            data = $.parseHTML(data);
            $.each( data, function( i, el ) {
                if (el.className == 'card') {
                    $(el).appendTo('.container');
                };
            });

            $('.card').each(function(i) {
                addMarker(i);
            });
        }
    });
});
like image 184
Viktor Maksimov Avatar answered Nov 22 '25 09:11

Viktor Maksimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!