-1

When i write the code as below

<p id="demo"></p>
<script>
document.getElementById('demo').innerHTML = 0xFF;
</script>

Then Browser shows the result 255 ( as it should be). But when i used

<p id="demo"></p>

below the script , browser do not show any thing. e.g.

    <script>
    document.getElementById('demo').innerHTML = 0xFF;
    </script>

<p id="demo"></p>
Why this ?
  • "does not show anything" ... except the **error** `"message": "TypeError: document.getElementById(...) is null",` – Jaromanda X Nov 12 '17 at 06:19
  • scripts are run when loaded, before the *following* HTML is parsed by the browser ... so, the element simply does not exist – Jaromanda X Nov 12 '17 at 06:19
  • 2
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – JJJ Nov 12 '17 at 06:21
  • In your last snippet, your javascript runs before the `p` element is processed in loaded to the DOM (document object model). So when you try to get it using `document.getElementById` the browser cannot find it. – Nisarg Nov 12 '17 at 06:21

2 Answers2

0

That is because the browser engine runs the script code first, in your case the dom does not have the element 'demo' yet so in console.log you get an error.

Script tags are best placed at the bottom of the page for this reason.

MartinWebb
  • 1,748
  • 1
  • 11
  • 12
0

The HTML is being loaded in order, so when the script is called that element does not exist. You can wait for the page to be loaded by doing something like this

<script>
    window.addEventListener('load',()=>{
        document.getElementById('demo').innerHTML = 0xFF;
    });
</script>

<p id="demo"></p>
Lilith
  • 437
  • 2
  • 11
  • Also, @MartinWebb gave a good point, adding the scripts inside the body before the html is not a good practice. You could consider putting it at the bottom of the page or adding the async attribute to the script element and putting it in the head. – Lilith Nov 12 '17 at 06:28
  • Ok . In this way, now browser shows the output but please explain the second parameter " ()=> " in window.addEventListner('load' , ()=>) – kashif Riaz Nov 12 '17 at 06:36
  • It is another way to write a function, you can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Lilith Nov 12 '17 at 06:39