Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .append() in for loop

I tried looking for an answer here but all of the questions related to my issue are a bit too complicated for someone who just started learning JavaScript like me.

I want to create a grid of divs with js/jquery based on user input (eg: if user chooses width = 16, then he will see a 16x16 grid).

Now, I figured, I'll add a DOM element with var $smallDiv = $('<div class="smallDiv"></div>');

And here is the loop that adds the needed number of divs based on user input:

function addDiv() {
$('#container').append($smallDiv);
}
for (i = 1; i <= divCounter * divCounter; i++){
addDiv();
}

The problem is that this will always create only one div. The loop runs the required number of times, I've checked this using console.log(). So it clearly works, but I get the feeling that each time it loops, the new div overwrites the previous. That wasn't my expectation of .append().

I've managed to get around the problem by making the $smallDiv variable a normal one (removing $ from its value, making it just text) but I would love to know how are these two variables different and why does one work in the above scenario but the other does not.

And make it easy on me, I just started learning JS/jQuery.

like image 345
Lessar277 Avatar asked Sep 08 '15 03:09

Lessar277


People also ask

How to use for loop in append in jQuery?

In the loop, you are appending the same dom element reference( $smallDiv ) multiple times, which means the element will be added only once. Instead in each iteration of the loop, you need to create new instance - you can use . clone() to do that.

Can we use for loop in jQuery?

You can use a JavaScript for loop to iterate through arrays, and a JavaScript for in loop to iterate through objects. If you are using jQuery you can use either the $. each() method or a for loop to iterate through an array.

How do you use append in for loop in Python?

You can append a list in for loop, Use the list append() method to append elements to a list while iterating over the given list.


1 Answers

In the loop, you are appending the same dom element reference($smallDiv) multiple times, which means the element will be added only once.

Instead in each iteration of the loop, you need to create new instance - you can use .clone() to do that.

function addDiv() {
    $('#container').append($smallDiv.clone());
}
like image 64
Arun P Johny Avatar answered Sep 18 '22 03:09

Arun P Johny