1

I am having a little problem, I can not add data to an existing element, so here is my Html code ( 1 line ):

<div id="lista"></div>

And here is my script :

var text = "ok";
for(var i=0; i<3;i++){
   text += "<p>text"+i+"</p>";
}

alert(text) // shows the expected data : ok<p>text0</p><p>text1</p><p>text2</p>
document.getElementById("lista").innerHTML = text;

But nothing is added to my page, And Rather than using innerHtml I used textContent, but it seems it is not working.

I followed a tutorial for begginers but as you can see, I dont get the expected results, any help would be much appreciated.

  • 4
    Your code as presented should work, but in the real thing do you get any errors in the browser's console? – Niet the Dark Absol Feb 03 '18 at 14:05
  • 1
    Perhaps your script is running before the page DOM has fully loaded? This is often the case if you load, and run, your JS in the tag. Try loading the JS just before , or wrap the script in a function that runs only when the page has finished loading. – MarsAndBack Feb 03 '18 at 14:06
  • I'm voting to close this question as off-topic because [it is indeed working...](http://jsbin.com/yarajemulo/edit?output) – Jonas Wilms Feb 03 '18 at 14:08
  • Yes I have An error, it tells me that document.getElementById(..) is null .. I dont know why .. :( –  Feb 03 '18 at 14:12
  • MarsAndBack and Andreas : you were right .. it worked, Thank you. –  Feb 03 '18 at 14:15
  • Mr Niet : Thank you for your time. –  Feb 03 '18 at 14:16

1 Answers1

0

Try to wrap your code document.addEventListener("DOMContentLoaded", to make sure the DOM are loaded before you execute the code.

Try this:

document.addEventListener("DOMContentLoaded", function() {
 var text = "ok";
 for(var i=0; i<3;i++){
    text += "<p>text"+i+"</p>";
 }

 alert(text) // shows the expected data : ok<p>text0</p><p>text1</p><p>text2</p>
 document.getElementById("lista").innerHTML = text;
});
<div id="lista"></div>
Eddie
  • 25,279
  • 6
  • 26
  • 53