perkface
perkface

Reputation: 113

Append Div with Multiple Child Divs Using For Loop

I realize that this has been asked a million times... but sorting through all the ones I've found, I haven't found one that really explains it well.

HTML:

<div id="alphabet"></div>

JS:

var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", 
                "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

var target = document.getElementById('alphabet');

for (i = 0; i < 26; i++) {

    var newLink = document.createElement('div');
    target.appendChild = newLink;
    newLink.innerHTML = alphabet[i];
}

alert(alphabet);
alert(newLink);
alert(target);

Obviously there is something I'm missing... With such a simple example I can't believe I'm having this much trouble. Any help is much appreciated, thanks in advance!

Upvotes: 4

Views: 2460

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Basically node.appendChild(node) is a function.

target.appendChild(newLink);

And your full code would be,

for (i = 0; i < 26; i++) {
 var newLink = document.createElement('div');
 newLink.innerHTML = alphabet[i];
 target.appendChild(newLink);
}

Upvotes: 2

Related Questions