0

i am writing a very simple application to get a element by id using javascript but it is returning null every time. I'm using chrome to test the application and unable to understand the cause. However, using the same id i'm able to do styling on it.

My Code:


<html>
    <head>
        <style>
            body 
            {
                padding-top: 10px;
            }
            #test
            {
                color:rgb(100,100,100);
            }
        </style>

        <script>
            var y = document.getElementById("test");
            document.write(y.innerHTML);
        </script>

    </head>
    <body>
        <div>
            <h3>History</h3>
            <h1 id="test">Number  of elements : </h1>
        </div>
    </body>
</html>

ErrorLog:


test.html:16 Uncaught TypeError: Cannot read property 'innerHTML' of null
    at test.html:16

Please help...

Anand
  • 249
  • 3
  • 18
  • 5
    The html elements are loaded in order, so at the time your code is executed the element you are trying to get is not yet on the DOM, move your JS code on the botom or execute it after the DOM is loaded. – xpy Apr 30 '20 at 07:12
  • Of course, it will return null, cause it's not yet appear (or known) when this JS section run. Move the script to the bottom or using `addEventListener` to run your function when your document is parsed. – Jack Ting Apr 30 '20 at 07:14
  • This would also create a bit of problem, because it will just duplicate the content that is inside the div. – dmanexe Apr 30 '20 at 07:16
  • Do. Not. Use. `document.write` – connexo Apr 30 '20 at 07:27

0 Answers0