0

<!DOCTYPE html>
<html>
 <body>
  <script>
   var aMessage = document.getElementById("aaa").innerHTML;
   console.log(aMessage);
  </script>
  <p id="aaa">Hello World!</p>
 </body>
</html>

When I access the document, the console error I am getting is:

Uncaught TypeError: Cannot read property 'innerHTML' of null

What am I missing?

xproofx
  • 3
  • 1
  • 2
    Scripts are evaluated while the document is being parsed. When your script runs, your `

    ` element is not yet part of the DOM.

    – Pointy Feb 04 '15 at 17:06
  • Ahh, thank you. I thought it would look through the entire document. – xproofx Feb 04 '15 at 17:07
  • It does look through the entire document _that has been parsed so far._ If that script ran after the document ready event, its location in the HTML would not matter. – Matt Ball Feb 04 '15 at 17:08
  • May I ask why this one works though? If I put that before my DIV elements, it does return an index. – xproofx Feb 04 '15 at 17:12
  • @xproofx - The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself. The returned list is live, meaning that it updates itself with the DOM tree automatically. See https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName – j08691 Feb 04 '15 at 17:20

1 Answers1

1

It's because you have the script tag before the element. Try it the other way around:

<!DOCTYPE html>
<html>
 <body>
  <p id="aaa">Hello World!</p>
  <script>
   var aMessage = document.getElementById("aaa").innerHTML;
   console.log(aMessage);
  </script>
 </body>
</html>

It's usually advised to put the script tag at the very bottom of your page. There's also a couple of events such as load and DOMContentLoaded that you can use to start your script once things have loaded

Bjorn
  • 60,553
  • 37
  • 128
  • 161
  • May I ask why this one works though? If I put that before my DIV elements, it does return an index. – xproofx Feb 04 '15 at 17:10
  • 1
    @xproofx `.getElementsByTagName()` **always** returns a NodeList, but in that case it would be an empty one. – Pointy Feb 04 '15 at 17:13
  • I understand now, thanks. – xproofx Feb 04 '15 at 17:16