0

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?

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35

1 Answers1

1

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++) {
Eranga Heshan
  • 5,133
  • 4
  • 25
  • 48