Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating div element with a for Loop

This is a really simple question but I don't know why it doesn't work. I have an array with 4 items inside. And I have a container which I would like to insert a number of divs based on the number of items in my array. I used a for loop for this but it is only creating one div. Should it not create 4 of the same div elements?

This is the code:

count = new Array['1', '2', '3', '4'];
container = document.getElementById('items');

for (i = 0; i < count.length; i++) {
  container.innerHTML += '<div id="items"></div>';
}
#items {
  width: 20px;
  height: 20px;
  background: gold;
}
<div id="items"></div>

This is the link http://codepen.io/2bu/pen/jyxNbw

like image 468
cord Avatar asked Dec 14 '25 21:12

cord


2 Answers

The way you are creating the array is incorrect.

Try this instead:

var count = ['1', '2', '3', '4'];

Note: Inside the for loop, you are creating elements that have the same ID. IDs should be unique.

Also, as mentioned you will want to append to the 'items' div instead of adding a new div with a duplicate id.

I would do something like this:

var count = ['1','2','3','4'];
var container = document.getElementById('items');
for(var i = 0; i < count.length; i++){
    container.append('<div>' + count[i] + '</div>');
}

And to improve the iteration:

var counts = ['1','2','3','4'];
var container = document.getElementById('items');
counts.forEach(function(count) {
    container.append('<div>' + count + '</div>');
});

It is rarely necessary to use for(var i = 0; i < x; i++). Using forEach, map or reduce are considerably better (code is more concise, temporary variables are unnecessary etc.).

like image 95
rasmeister Avatar answered Dec 16 '25 10:12

rasmeister


1)You cannot create more DOM elements with same id.Use classes instead.

2)You have to define the array in the following way: var count = ['1', '2', '3', '4'];

Here is the final code:

// var container = document.getElementById("container");
// for (var i = 0; i < array.length; i++) {
//    container.innerHTML += '<div class="box"></div>';
// } 
count = ['1','2','3','4'];
container = document.getElementById('itemsContainer');
  for(i = 0; i < count.length; i++){
    container.innerHTML+='<div class="items"></div>';
  }

var square= document.getElementsByClassName('items')[2];
square.style.backgroundColor='red';
.items{
  margin-top:10px;
  width:20px;
  height:20px;
  background:gold;
}
<div id="itemsContainer"></div>

If you want to access one items DOM element, you have to use document.getElementsByClassName() method which returns a NodeList.

var square= document.getElementsByClassName('items')[2];
square.style.backgroundColor='red';
like image 26
Mihai Alexandru-Ionut Avatar answered Dec 16 '25 10:12

Mihai Alexandru-Ionut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!