Create multiple elements

xoomer picture xoomer · Sep 19, 2015 · Viewed 20.8k times · Source

JavaScript

var textBlock = document.createElement('div');
textBlock.setAttribute('class', 'finalBlock');

var addFinalBlock = document.getElementsByClassName('block')[0];
addFinalBlock.appendChild(textBlock);

textBlock.innerHTML = "Make this block a text block";

// -------
var textBlock2 = document.createElement('div');
textBlock2.setAttribute('class', 'finalBlock');

var addFinalBlock2 = document.getElementsByClassName('block')[0];
addFinalBlock2.appendChild(textBlock2);

textBlock2.innerHTML = "Make this block a text block2";

// -------
var textBlock3 = document.createElement('div');
textBlock3.setAttribute('class', 'finalBlock');

var addFinalBlock3 = document.getElementsByClassName('block')[0];
addFinalBlock3.appendChild(textBlock3);

textBlock3.innerHTML = "Make this block a text block3";

// -------
var textBlock4 = document.createElement('div');
textBlock4.setAttribute('class', 'finalBlock');

var addFinalBlock4 = document.getElementsByClassName('block')[0];
addFinalBlock4.appendChild(textBlock4);

textBlock4.innerHTML = "Make this block a text block4";

I want to create 4 elements with different text. The class needs to remain the same. I think I am doing this with to much code.

Maybe anyone has some information how to make this code look more beautiful and more efficient?

Best wishes and thank you!

Answer

user3589620 picture user3589620 · Sep 19, 2015

If you do the same things a lot of times, use a loop. Store the different text in an array and go through it with forEach:

var text = ["text1", "tex2", "text3", "text4"];
text.forEach(function(el) {
    var div = document.createElement("div");
    div.className = "finalBlock";
    div.innerHTML = el;
    document.body.appendChild(div);
});

or with a for loop:

var text = ["text1", "tex2", "text3", "text4"];
for(var i = 0; i < text.length; i += 1) {
    var div = document.createElement("div");
    div.className = "finalBlock";
    div.innerHTML = text[i];
    document.body.appendChild(div);
}

Demo