-1

I have the following HTML and Javascript code, but Chrome cannot allow me to run it, can anybody help me fix it up. HTML code is:

    var myNodelist = document.getElementsByTagName("p");
    document.getElementById("demo").innerHTML = "The innerHTML of the second paragraph is: " + myNodelist[1].innerHTML;
  <p>Hello World!</p>
    <p>The DOM is very useful!</p>
    <p id="demo"></p>

The error message of Chrome is: Uncaught TypeError: Cannot read property 'innerHTML' of undefined

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
Tao Xie
  • 11
  • 4
  • 1
    Is your script included above or below the HTML code you show us? – Cymen Jun 27 '15 at 22:24
  • If I put your exact code in a runnable snippet it works fine in Chrome. The code in itself is not wrong, but Cymen has a point: The script runs as soon as it is parsed. If it is at the top of the document, the element is not yet available. – GolezTrol Jun 27 '15 at 22:26
  • `getElementsByTagName` returns a `HTMLCollection`, not a `NodeList`. – Oriol Jun 28 '15 at 00:00

1 Answers1

1

The most likely problem is you are including your JavaScript in the header of the HTML and it is running before the rest of the page is parsed by the browser. So the DOM lookup document.getElementById("demo") returns undefined. Either move your JavaScript to the bottom of the HTML file or make it wait until the DOM has finished rendering (see What is the non-jQuery equivalent of '$(document).ready()'?).

Community
  • 1
  • 1
Cymen
  • 14,079
  • 4
  • 52
  • 72
  • I got it now! I do put the script code at the bottom of HTML, so if I put my script code in another file and include it in the HTML header, how to make it work? – Tao Xie Jun 27 '15 at 22:32
  • @xietao0221 Then you need to read what I linked to at the bottom and use that to run your script when the document is "ready" (HTML has been parsed to DOM). – Cymen Jun 27 '15 at 22:34
  • @xietao0221 Or you could just put it at the bottom on the other page -- it doesn't need to be in the header. – Cymen Jun 27 '15 at 22:34