-1

I have simple code:

var aso=document.querySelector("body");
aso.style.background="yellow";

This is written in separate .js file. When you open the page, it is showing error:

simple.js:2 Uncaught TypeError: Cannot read property 'style' of null
    at simple.js:2

But when I run this code in console window, it works fine, but showing error in separate JS file.

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
Md Ashraf
  • 19
  • 2

2 Answers2

0

It is probably because you are linking your JS file in the HTML file before the DOM is loaded, so your query selector can't find desired element.

Try to move your <script> tag to the bottom of the HTML file.

Petr Jelínek
  • 694
  • 4
  • 22
0

its a dom problem you must run scripts after dom loaded there are many ways to execute js functions after dom

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <script>
    // self executing function here
    (function() {
       // your page initialization code here
       // the DOM will be available here
        var aso=document.querySelector("body");
        aso.style.background="yellow";
    })();
    </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
<script>
    document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
    var aso=document.querySelector("body");
        aso.style.background="yellow";
});
</script>
</body>
</html>
Dev Khalil
  • 111
  • 1
  • 5