Cannot read property style of null

Hi,

The following code generate the error “Type error: Cannot read property style of null”

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Query select</title>
    <script src="domtest.js"></script>
</head>
<body>
    <h1>My name is Sammy</h1>
</body>
</html>
var h= document.querySelector("h1");
var isGreen=false;

setInterval(function(){
    if(isGreen){
        h.style.color="black";
    } else {
        h.style.color="green";
        }
        isGreen=!isGreen
},1000)

I know where is the problem its in this line:
“var h= document.querySelector(“h1”);”
because I paste it in the console and returned h=null
but I don’t know why this happened,

It actually works, i put it on jsfiddle.net and it works, change the color from black to green and keep going. Probably the problem is that you put the script on the head before the body of the webpage is loaded. So i am assuming that on that time nothing inside <body> tags exist. Try putting your link at the end of body just before the cosing tags

Thank you for your response actualy I have a seperate js file and I test the connectivity with the html.

Maybe it is because your are called var h= document.querySelector("h1"); before the DOM was render, try to move the script before close the </body>

1 Like

I just created an account to say ‘THANK YOU!’ : )