-2

I just started learning DOM Manipulation and want to do a simple task of changing the font color of h1 using javaScript but I am getting this error - "Cannot read property 'style' of null ". My js file is connected to html but the next line is not working. Please help.

demo.html

<!DOCTYPE html>
<html>
<head>
    <title>My Site</title>
    <script type="text/javascript" src="demo.js"></script>
</head>
<body>
<h1>My Website</h1>
</body>
</html>

demo.js

alert("connected");
var h1=document.querySelector("h1");
h1.style.color="pink";
Subham Kaps
  • 163
  • 1
  • 2
  • 10

2 Answers2

0

you must load link your js at the end of body. you are mainpulating DOM but it hasn't loaded completely, thats why it is giving you null value. try this:

<!DOCTYPE html>
<html>
<head>
    <title>My Site</title>
</head>
<body>
<h1>My Website</h1>
    <script type="text/javascript" src="demo.js"></script>
</body>

or you can use defer in your script tag

<!DOCTYPE html>
    <html>
    <head>
        <title>My Site</title>
        <script type="text/javascript" src="demo.js" defer></script>
    </head>
    <body>
    <h1>My Website</h1>
    </body>

</html>
Dij
  • 9,501
  • 4
  • 15
  • 34
0

You must wait that the DOM is loaded.

document.addEventListener('DOMContentLoaded', function(){"put your code here"});