Overusing For Loops for Cloning in JavaScript

REVISED: (I have pinpointed the issue previously discussed in the comments)

this is the code I am working with:

<script type="text/javascript">
        for(var i=0; i<5; i++){
            $(".image-wrap").clone().appendTo(".container").attr('id', ("reason" + i));
        }

</script>

oddly enough, when implementing this method, I end up with one "image-wrap" div having the ID of "reason0" as intended. However, subsequent repetitions result in two occurrences of "image-wrap" with "reason1," followed by four instances labeled "reason2," and so forth. Can you identify what may be causing my loop to malfunction?

Answer №1

You will find two occurrences of "image-wrap" with "reason1", followed by four instances of "image-wrap" with "reason2," and so on.

The reason for this is because the code $(".image-wrap").clone() targets every element with the class "image-wrap."

If you only want to clone the first occurrence of .image-wrap, you can use the :first pseudo-selector. Check out the modified script below..

$(".image-wrap:first").clone().appendTo(".container").attr('‌​id', ("reason" + i));

Learn more about the :first pseudo-selector here

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

Is there a way to use XMLhttprequest to send a post request to my personal Node server using vanilla javascript?

I have encountered an issue while trying to send data to Node using XMLhttprequest. The data I am attempting to send looks like this (/q/zmw:95632.1.99999.json). My connection to Node is set up correctly, but I was receiving an empty object. So, I decided ...

The Ajax post function successfully executes on the first attempt, but on subsequent tries it does

My goal is to send data from a forum asynchronously to a PHP page and display the response in a specific ID without refreshing the page. The first time I submit, everything works perfectly. The text is successfully sent to append.php and the new list of i ...

Identifying when several asynchronous JavaScript $.ajax requests have finished

I have a JavaScript function that runs a loop and makes asynchronous AJAX calls. I need to wait for all the AJAX calls to complete before updating the UI. Here is the loop: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { ...

Adding a feature to a React project

After importing the following code snippet into a test file: https://i.sstatic.net/i44pI.png Everything seems to be working fine. However, issues arise when trying to import it into another file—here is what I'm using: https://i.sstatic.net/dsBQu ...

Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE: The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here i ...

Explore and choose JSON data for specific items depending on an array of criteria

I need to extract specific objects from a JSON file by matching them with values stored in an array. To illustrate, I have an array var list = ['test1', 'test2']; and there is a variable containing the following data: var data = [ ...

Enhance the appearance of your Dojo TabContainer when viewing in Internet Explorer

Firefox seems to handle the following code without any issues: < div style="position:absolute;top:0px;margin-top:60px;bottom:0px;width:100%"> < div id="mainTabContainer" dojoType="dijit.layout.TabContainer" style="width:100%;height:100%"> {% fo ...

Perform the function with the value of the currently selected option

Despite selecting an option, a message still appears stating "Please choose something." This function works with only one dropdown list, but encounters issues when there are two or more. (In this example, the variable 'sport' is document.getElem ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

Customizing the navbar to be inverse on each webpage using CSS, PHP, and Bootstrap

Dealing with a Bootstrap navbar across multiple pages on my website is becoming a hassle. Every time I need to make a change, I find myself jumping from one page to another just to update it. My objective is to have the ability to edit the navbar in one ce ...

Node server encountering issue with undefined data in POST request

I have been working on an Angular2/Node.js application. Everything seems to be working fine when I retrieve an object from the Node server, but I'm facing an issue when trying to post data to the server. The request.body always shows as undefined. Can ...

Display jqgrid with borders and insert extra headers text at the top of the grid

function generateTableWithText(){ $("#active_grid").jqGrid("exportToHtml",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, autoPrint : true ...

The $scope variable is not retaining the value for the ng-repeat directive

I'm struggling to implement an ng-repeat on data fetched from an API in JSON format. The issue I'm facing is that even though I can see the data in $scope.wines when I console.log() before the function ends, the data seems to disappear by the end ...

Creating a HTML5 Geolocation object using Python: A step-by-step guide

For my software analytics testing, I am looking to send GET requests with a geolocation object that includes variable timestamps and locations. The website utilizes the HTML5 navigator.getcurrent.location() function. While I can use the random module to r ...

Build a flexible Yup validation schema using JSON data

I am currently utilizing the power of Yup in conjunction with Formik within my react form setup. The fields within the form are dynamic, meaning their validations need to be dynamic as well. export const formData = [ { id: "name", label: "Full n ...

Problems arise when using $(window).width() in conjunction with scrolling functionality

I am attempting to ensure this code only activates when the device window exceeds 960px and triggers when the window scrolls down 700px. The second condition is functioning as intended, but the first condition is not working properly. The code functions f ...

Is it possible to simultaneously center and display an iframe inline?

I have a YouTube video that I'm trying to center within a div. After adding display: block; to the CSS following advice from How to center an iframe horizontally?, it centers correctly, but now I want to display two images inline next to the iframe ...

What is the best way to ensure that a <div> extends all the way to the bottom?

My goal is to have this element reach the bottom of the screen, but I also have a header which complicates things. Setting height: 100%; or 100vh results in the page being too big and scrollable. I don't want to manually calculate it because of respon ...

reCAPTCHA failing to prevent users from accessing their accounts

I recently implemented Google reCAPTCHA on my login form to combat spam. Despite following all the necessary steps to set it up, users are still able to log in without checking the checkbox, which is not ideal. My initial thought was that the issue might ...

Transforming a dynamic HTML layout into a non-responsive one: "RESPONSIVE NO MORE"

I'm currently working with an HTML document that has a responsive design. However, I now need to make it non-responsive. Can someone advise me on the most efficient and fastest way to do this? I attempted using min-width for both html and body, but ...