0

The following line of code (in my Javascript file) :-

var header = document.getElementById("theheader");

is resulting in header having a "null" value. Here, "theheader" is the ID of a "h2" type header in my HTML file.

The desired output is:-

<h2 id="theheader" style="color: rgb(114, 58, 76);">

The script tag of the JS file is defined within the head element of the HTML file.

The same line of code would work perfectly in any browser console by giving the desired output i.e. Even though this issue has been handled before, I could not find the answer as to why the same code above is working in the browser console and not working in IDE's like VSCode, Atom and others?

I would be thankful if anyone could provide me the answer for the above query, specially the one in bold font.

Arnab Sinha
  • 301
  • 2
  • 7
  • 17

1 Answers1

3

One possible reason could be that your code is running before the DOM is fully loaded. Wrap your code with DOMContentLoaded:

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    //Intro
    alert("Hey! Welcome to my page!!");
    var a = prompt("How are you today?");
    alert("Happy to know that you are " + a);
    var header = document.getElementById("theheader");
    console.log("h2 is " + header);
    header.style.color = "red";   
    function getRandomColor() {
        var letters = "0123456789ABCDEF";
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
    function changeHeaderColor(){
        colorInput = getRandomColor()
        header.style.color = colorInput;
    }

    setInterval(changeHeaderColor,500);
  });
</script>

<h2 id = "theheader"> Arnab Sinha </h2>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    Your solution was helpful in achieving what I wanted. – Arnab Sinha Jan 02 '19 at 09:32
  • Hello, I did not understand the second parameter in the addEventListener() function. What does it do and how does it work? Hope for your help. @Mamun – Arnab Sinha Jan 02 '19 at 12:39
  • @ArnabSinha, the first parameter is the event and the second is the function which will be executed when the even is fired. In this case the event will be fired when the DOM is fully loaded and then the code inside the function will be executed.....hope it is clear now..... – Mamun Jan 02 '19 at 12:56