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

Issues with external javascript link functionality

I'm having trouble connecting my external JavaScript file to my HTML code. I'm attempting to concatenate two strings using an input function and then display the new string in the empty text field. What could be causing this issue? Appreciate an ...

Field for user input featuring a button to remove the entry

I am attempting to add a close icon to a bootstrap 3 input field, positioned on the top right of the input. Here is what I have tried so far: https://jsfiddle.net/8konLjur/ However, there are two issues with this approach: The placement of the × ...

What is the best way to integrate custom JavaScript files into a Vue project?

I recently downloaded an HTML template from a website and now I am looking to convert the entire template into a Vue CLI project. The template includes jQuery and other custom JavaScript files. While I was able to use npm packages for jQuery and Bootstrap, ...

Breadcrumb floating to the right, yet it still manages to obstruct other content, forcing it into a

Within the Breadcrumbs section, I have the path home/profile The desired layout involves floating the Breadcrumbs to the right while keeping the Other contents unfloated to the left. Ver1 -------------------- home/profile -------------------- Ot ...

This code snippet results in the property being unrecognized

I recently wrote this block of code and encountered an error while trying to run the alert function. It keeps telling me that 'this.words' is not defined. I suspect the issue lies within the jQuery portion, as I am able to access the array where ...

The jqGrid is not showing the AJAX JSON data as expected

Currently, I am exploring jqgrid and trying to figure out how to display data in another jqgrid when clicking on a specific colmodel. The retrieved data from the server goes through a function and reaches the grid, but no information is displayed without a ...

Selecting attribute using a variable in jQuery is a common practice in

var attr = myopts.addAttributeFromChemSelect; alert(ob.attr(attr)); is undefined var attr = myopts.addAttributeFromChemSelect; alert(attr); is 'tip-ref' var attr = myopts.addAttributeFromChemSelect; alert(ob.attr('tip-ref'); is &ap ...

Is this filter selector in jQuery correct?

It appears to function correctly, but I am unsure if there is room for improvement. I aim to target any HTML element with a class of edit-text-NUM or edit-html-NUM and adjust its color. This is the code snippet I am currently utilizing... jQuery(document ...

Issues with my transpiled and typed TypeScript npm module: How can I effectively use it in a TypeScript project?

I'm trying to experiment with TypeScript. Recently, I created a simple "hello world" TypeScript module and shared it on npm. It's very basic, just has a default export: export default function hello(target: string = 'World'): void { ...

Having trouble with ReactJS updating the state in the correct format using moment?

In my ReactJS project, I am using a datepicker feature. However, I have encountered an issue where the state is not being updated with the selected date value after formatting it using moment.js. const [selectedDates, setSelectedDates] = useState([]) ...

While validating in my Angular application, I encountered an error stating that no index signature with a parameter of type 'string' was found on type 'AbstractControl[]'

While trying to validate my Angular application, I encountered the following error: src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used ...

React - Error: Unable to access the 'props' property because it is undefined

I am working on implementing a click event to delete an item from my list, but I keep encountering the error message "TypeError: Cannot read property 'props' of undefined" whenever I click on it. Although I am striving to follow ES6 standards as ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

What is the best way to display a multi-state component that includes an API fetch?

Currently, my tech stack includes React and Node.js. Within my project, I have a component named ItemList. This particular component fetches data from an API in the componentDidMount() method to facilitate rendering a "loading state." My objective is to ...

Attempting to execute a PHP script through a JavaScript if statement

I have a form that requires validation with JavaScript. In one of the if statements, after all other conditions have been validated, I want to execute my PHP script that updates an SQL database with one of the passwords. Here is the final validation code: ...

Wagtail Django TableBlock not showing up properly on the webpage

Recently delving into the world of Django and programming, I decided to incorporate Wagtail into my website. However, I've encountered a roadblock with the 'TableBlock' functionality Despite setting up the model and block correctly, I&apos ...

Alignment problem

In my design, I have a toolbar with flex display and I am trying to center my span element within it. However, I seem to be missing something in the CSS. CSS .toolbar { position: absolute; top: 0; left: 0; right: 0; height: 60px; d ...

Switch out everything except for the initial one

Can all instances be replaced except for the first one? For example, 123.45.67..89.0 should turn into 123.4567890. Edit: Specifically seeking a regex solution. I am aware of how to achieve it through concatenation or using the index. ...

The issue of TypeScript failing to return HTML Template Element from Constructor typing is causing complications

There is a restriction on using new to create an instance of Template, which extends an HTMLTemplateElement. To work around this limitation, I fetch and return an HTMLTemplateElement by using document.getElementById(id) within the constructor of the Templ ...

The importance of understanding Req.Body in NODE.JS POST Requests

Currently, I am developing a Node.JS application that interacts with a MySQL database. The app retrieves data from the database and displays it in a table using app.get, which functions correctly. The issue I am facing is that when utilizing app.post, re ...