Execution of Javascript code does not provide the expected output when run via VS Code

I've attempted numerous times, but the desired output doesn't appear when I run it through VS Code. However, this code runs smoothly and produces the desired output when executed in Replit's online code editor. Can anyone offer assistance?

let age = prompt("Please 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"
}

Answer №1

I have encountered the issue you mentioned in this specific manner:

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

The problem arises when running the script, causing a pause in the parsing process. As a result, only elements that have been parsed up to that point are available. Essentially, only these sections have been processed:

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

At this stage, there is no <body> tag that has been parsed for the script to act upon. So, when trying to access document.body, the output is null. Attempting to modify document.body.style will result in an error, triggering a message (

Uncaught TypeError: Cannot read properties of null (reading 'style')
at test.js:11:17) instead of changing the color as intended.

To address this issue, one solution is to relocate your script after the <body> tag, like so:

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

Alternatively, you can add the defer attribute to your script tag, allowing the parser to wait until the body content is fully loaded.

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

There is also the option of using the async attribute for scripts that do not cause immediate pausing of the parser. However, in this case, it may not be suitable due to potential race conditions affecting the order of execution. The parser usually reaches the <body> element faster than fetching and executing a separate JavaScript file.

This post elaborates on the distinctions between regular script loading, async, and defer attributes:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get the value of a JSON in template strings

After querying objects from a table, they are stored in objarr. How can I retrieve these values in the UI using JavaScript? from django.core.serializers import serialize json = serialize("json", objarr) logging.debug(type(json)) response_dict.update({ ...

What is the method to define the maximum width for a BootstrapTable while also trimming any data that exceeds this specified width?

In my ASP.NET Web Forms project, I am utilizing Bootstrap 5.2 for a BootstrapTable, which is currently defined as follows: <table class="display table table-bordered table-striped w-100 tables" ...

Navigating by Typing in the URL Bar in React

Whenever I paste a valid URL and press enter, the useEffect function in the parent component does not get triggered. However, if I reload the page, it works fine. Here is the code snippet: Routing path <Route path="/search" element={<Searc ...

Troubleshooting: My jQuery script for fading in content upon document ready is not

I'm currently working on a website where I want everything to fade in when the user enters the site. Take a look at my code: var celyLogin = $(".container"); $(document).ready(function () { /*! Fades in page on load */ $("container") ...

Including an <a> tag within a JavaScript variable to utilize in an HTML statement

I want to wrap an <a> element around a JavaScript variable containing a string. The desired output should be the 'copyright symbol' followed by the 'companyName' linked as an HTML link and then the current year's date. JavaS ...

Shapes in Three.js with multiple colors

As a newcomer to Three.js and webGL programming, I have successfully created a cone and a cylinder in my scene using the script provided below: var scene; var camera; var renderer; var createACone = function() { // Cone creation code here } var creat ...

JavaScript Flash player for iPad

As many of us know, the iPad does not support Flash. However, I am curious if the iPad sends any specific error messages that can be captured using Javascript. I realize one method is to detect the iPad from the user agent string, but I am interested in w ...

modify input type in Reactjs based on boolean state dynamically

I am currently working on implementing a checkbox feature that allows users to toggle between viewing their password or keeping it hidden. I decided to use Material UI React for the user interface elements. The checkbox is set up and functioning properly. ...

Guide on how to execute jasmine tests coded in TypeScript for Node.js applications

I am eager to test my express application developed in TypeScript. I am utilizing jasmine for writing test cases, webpack for bundling TypeScript files to JavaScript, and karma as the test runner. Please locate the following files: // about.service.ts - ...

Set the input's type attribute to 'checkbox' to address an issue with Internet Explorer

This issue is specific to Internet Explorer, as other browsers like Firefox, Chrome, Safari, and Opera are functioning correctly. Instead of displaying checkboxes, it shows a value box... Here is the code snippet: <html> <head> <title> ...

Angular Material selectionChanged function is providing the previous step instead of the current step

I need to make a page with two columns: one for a vertical stepper and the other for step descriptions. I want the description to update based on the current step selected. However, I am running into an issue where the selectedIndex shows the previously ch ...

The parameter necessary for [Route: admin.request.update] is missing. The required URI is admin/request/{request}, and the missing parameter is 'request'

When attempting to access detail.blade.php, I encountered an error stating "Missing required parameter for [Route: admin.request.update] [URI: admin/request/{request}] [Missing parameter: request]." Despite following the steps and codes exactly as in my pr ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

Incorporate JavaScript .js file into the webpage asynchronously to invoke a web service

JavaScript File: JScript.js function Helloworld() { $(document).ready(function () { $.ajax ({ type: "POST", url: "Default.aspx/Helloworld", contentType: "application/json; charset=utf-8", dataType: "json", a ...

Retrieving information from a JSON file using JavaScript

My code snippet looks like this: { "badge_sets":{ "1979-revolution_1":{ "versions":{ "1":{ "image_url":"https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67f ...

Is there a way to position two bootstrap col divs in alignment with a third col div situated to the left?

I'm attempting to achieve the desired layout shown in this result: https://i.sstatic.net/B3EDr.png Here is the code I have been working with: <div class="container"> <h1>Welcome Dennis,</h1> <div class="col-12 card card- ...

JavaScript parsing error occurred

Encountering a parsing error in my JavaScript code when deploying Firebase functions. The error mentions an unexpected token, indicating there might be a character out of place. I've been stuck on this issue for weeks now. Any assistance would be grea ...

Rendering with Node.js Express and Mongoose after saving data

I recently started diving into Node.js Express and Mongoose while constructing a basic blog platform. My focus is on establishing routes for handling simple database tasks, but I'm feeling uncertain about managing asynchronous functions and ensuring ...

Removing all Null Form Inputs from the Document Object Model upon Submission utilizing JavaScript

I am currently working on a conditional Shopify form that was passed down to me from another developer. The form utilizes JavaScript/Jquery for field validation, ensuring that all mandatory fields are completed before proceeding to the next step. After mak ...

Convert specific form inputs into an array

I have a form that includes various inputs, but the ones I am focusing on are labeled attributes[] and options[$index][]. Here is an example of the data found in my attributes[] input: Array ( [0] => Size [1] => Color [2] => Material ) Not ...