-3

I have tried many times it is not showing the desired output if i run it through vs code but this code works well and produces desired output if i run it in replit online code editor Someone Please help!

let age = prompt("enter your age")
age = Number.parseInt(age)
if (age <= 10) {
  document.body.style.background = "red"
}
else if (age > 10 && age <= 18) {
  document.body.style.background = "yellow"
}

else {
  document.body.style.background = "green"
}
phuzi
  • 12,078
  • 3
  • 26
  • 50

1 Answers1

0

I can reproduce your issue this way:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
    <script src="./test.js"></script>
</head>
<body>
</body>
</html>

The problem is, in order to run your script, it will pause the parsing, and when your script is run, only the elements it has encountered are available. So basically, it has only parsed these parts:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
    <script src="./test.js"></script>

It has not parsed a <body> tag for it to process at that point. So, when it attempts to get document.body, the result is null, and trying document.body.style results in an error, so it throws an error (Uncaught TypeError: Cannot read properties of null (reading 'style') at test.js:11:17) instead of changing the color.

To solve this, you may either move your script somewhere after <body>, for example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
</head>
<body>
    <script src="./test.js"></script>
</body>
</html>

Or add defer attribute to your script tag so that the parser waits for the body to be finished.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
    <script src="./test.js" defer></script>
</head>
<body>
</body>
</html>

There is also async attribute for a script that won't pause the parser immediately, but in this case it's not appropriate (it introduces a race condition; but then the parser will win, it's quicker to reach <body> than to request a separate js file)

This thread describes the difference between regular script, async and defer: https://stackoverflow.com/a/39711009/4225384

qrsngky
  • 2,263
  • 2
  • 13
  • 10