0

for(var i=0;i<100;i++) {
var para = document.createElement("p");
var node = document.createTextNode("This is just dummy data...but a very long one!!!.");
para.appendChild(node);
var element = document.getElementById("main");
element.appendChild(para);
}
<html>
<head>
<title>Experiment -II</title>
<script type="text/javascript" src="exp.js"></script>
</head>
<body>

  <div id="main">
  </div>

</body>
</html>

I worte the code and tried but i get the error 'document.getElementById(...)' is null or not an object' even though i think object is not null.

Why am i getting this? Is it because i have left the "main" section empty?

1 Answers1

2

It's because your script is being run before the <div> has loaded.

Move your script to the bottom of the document to ensure the element has been loaded, or use a DOMContentLoaded event handler.

Matti Virkkunen
  • 58,926
  • 7
  • 111
  • 152