Is it possible to iterate through div elements using .each while incorporating .append within an AJAX call?

After sending AJAX requests and receiving HTML with multiple div elements (.card), I am using .append to add new .card elements after each request, creating an infinite scroll effect. However, I am facing issues when trying to use .each to iterate over all .card elements on the 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);
}
});

This approach is not functioning as expected.

With each AJAX request, I am observing that the count begins from zero on the new .card divs.

Answer №1

If you are working with a scenario where you have a container element

<div class="container"></div>
and appending cards within it using
<div class="card"></div>
, then the script below would be appropriate:

$(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);
            });
        }
    });
});

Answer №2

Give my method a shot, it might be just what you need.

$(function(){
$.ajax({
    method: "GET",
    url: "information.action",
    success: function(response){
        $(response).find(".item").each(function(index, object){
                $(".container").append(object);
        });
        $('.item').each(function(idx) {
            addMarker(idx);
        });
    }
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can Jquery be used to target elements that have certain value(s) in their data attribute array?

I have the following elements: <div data-tags="[8,18,32,52,53,56]"></div> <div data-tags="[8,2,3]"></div> <div data-tags="[4,6,10]"></div> How can I select elements that contain "8" in thei ...

Challenge with form validation

Currently, I am utilizing the jQuery validation plugin to handle form validation. However, I have encountered an issue when using inline labels. Here is an example: <input type="text" name="myinput" value="Enter your ...."> In this specific scenar ...

In my VueJs project, I developed a custom button component that includes a loader feature. I initially passed the loader as a prop, but I am currently facing challenges integrating it with a method in another VueJs page

Here is an example of my component: <button class="BtnLoader btn btn-primary-contained btn-iconed btn-mobile btn-important" @click="onClick" :aria-label="label" :title="title"> <i v-if="loader" cla ...

In Vue2, you can utilize $ref to retrieve information from a child component and transfer it into the parent component's data

Trying to access child components' data in Vue2 and move it into the parent component's data without triggering an event. Saving count:20 from the child component into the parent component in the example below. Please let me know if there are any ...

What is the method for storing API status JSON in the state?

Can anyone help me figure out why the json in the register state is returning an empty object after console.log(register); from that state? import React, { useEffect, useState } from "react"; import { Formik } from "formik"; // * icons ...

Retrieve information from a JSON file containing multiple JSON objects for viewing purposes

Looking for a solution to access and display specific elements from a JSON object containing multiple JSON objects. The elements needed are: 1) CampaignName 2) Start date 3) End date An attempt has been made with code that resulted in an error displayed ...

The close button on my modal isn't functioning properly

There seems to be an issue with the close button functionality. <div class="modal fade show " id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="display: block;left: -6.5%;"> <div class="modal-dialog" ...

Prevent the countdown timer from resetting every time I refresh the page

Whenever I refresh my page, the timer starts over. I want it to pick up from where it left off until it reaches 0. This is my JavaScript code for handling the timer: var target_date = new Date().getTime() + (1000*3600*48); // set the countdown date var ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...

Having trouble integrating the css and js animation files into my Django project

settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '@6qt%i+0&_=z0#zl^+!u3bw6c7dmg4e3khboj%7s7439z9#ky(' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin& ...

Personalized jQuery mask customization

After experimenting with a masking function that conceals numbers based on a specific pattern, I am now looking to make it more flexible for users. For instance, if a user types 123456789, the field will display as XXX-XX-6789. Currently, the pattern is ...

Elements from Firebase failing to appear in Angular Grid

I'm struggling to populate items within this grid sourced from Firebase. I was able to make it work with a custom Service that returned a fixed array. I can confirm that the data is being received by the browser as I can log it out in JSON format lik ...

Deliver an index.html file upon server creation

My goal is to have the server load a file called index.html when it is created. Currently, when I run the server.js file using node, it responds with text using res.end("text"). However, I want the index.html file to be displayed instead. I attempted to a ...

Unsubscribing from a service method in Javascript using RxJS

After clicking a button, a function is triggered to execute. The function includes an method called "executeAction" that retrieves the current view and then passes it as a parameter to another view for future reference. async executeAction(action: ...

What is the hexadecimal color code for a specific element's background?

How can I retrieve the background color code of a specified element? var backgroundColor = $(".element").css("background-color"); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="elemen ...

Vue Quasar Drawer Layout with Bottom Bar

Struggling to implement a footer in my q-drawer. Below is the template and component code I am currently using: <template> <q-layout view="hHh lpR fFf"> <q-header elevated> <q-toolbar> <q-btn flat de ...

Avoiding special characters in URLs

Is there a way to properly escape the & (ampersand) in a URL using jQuery? I have attempted the following methods: .replace("/&/g", "&amp;") .replace("/&/g", "%26") .replace("/&/g", "\&") Unfortunately, none of these are y ...

What is the process for retrieving the address of the connected wallet using web3modal?

I've been working on an application using next.js and web3. In order to link the user's wallet to the front-end, I opted for web3modal with the following code: const Home: NextPage = () => { const [signer, setSigner] = useState<JsonRpcSig ...

Are max-width:auto and max-width:100% the same thing?

Does max-width set to auto have the same result as setting max-width to 100% If not, what is the distinction between them? ...

Showcasing a variety of products on a single webpage in Magento

In my current project, I have a module that is set up to respond to Ajax requests. One of the tasks I'm working on involves rendering multiple products and retrieving the resulting HTML. Below is a snippet of code from my controller where I have hardc ...