Tudor Stanciulescu
Tudor Stanciulescu

Reputation: 65

Dynamically create <div> element and append something in for loop

I am trying to create dynamically some divs and append some data to these divs. I have tried this:

var array = ["name1","name2","name3"];
for(let i=0;i<array.length;i++) {
    var newElement = document.createElement('div');
    newElement.id = array[i];
    newElement.className = "names";
    newElement.innerHTML = array[i];
    document.body.appendChild(newElement);
}

The error I get is:

TypeError: Cannot read property 'appendChild' of null

Edit:

if i put the script code in body tag, it's working. i don't understand why, but it's working. Can anyone help me understand why?

Upvotes: 0

Views: 793

Answers (1)

Eranga Heshan
Eranga Heshan

Reputation: 5814

In Javascript, array.legth is a property not a function.

Try changing

for(let i=0;i<array.length();i++) {

into,

for(let i=0;i<array.length;i++) {

Upvotes: 1

Related Questions