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.
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.
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.
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With