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?

3
  • Sorry for that, my mistake, but it's still not working. TypeError: Cannot read property 'appendChild' of null Commented Oct 8, 2020 at 6:45
  • update: if i put the script code in body tag, it's working. i don't understand why, but it's working. thx anyways! Commented Oct 8, 2020 at 6:49
  • See stackoverflow.com/a/9916754/3153169 Commented Oct 8, 2020 at 13:47

1 Answer 1

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++) {
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, that was my mistake, but it's still not working. TypeError: Cannot read property 'appendChild' of null
Update: it's working if i put the script in <body>. Anyway. thx for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.