The function is defined, but it cannot be set to null

Having trouble understanding this error message "Cannot set properties of null." I'm attempting to update the innerHTML with the output text from four functions that my button triggers. However, it seems to be stopping at the first function now even though it was working fine before.

Any suggestions on how to resolve this issue?

var calories;
var fat;
var saturatedFat;
var salt;
var carbohydrates;
var sugars;
var portionsize;

function getstats() {
    calories = parseFloat(document.getElementById("caloriesinput").value);
    fat = parseFloat(document.getElementById("fatinput").value);
    saturatedFat = parseFloat(document.getElementById("saturatedFatinput").value);
    salt = parseFloat(document.getElementById("saltinput").value);
    carbohydrates = parseFloat(document.getElementById("carbohydratesinput").value);
    sugars = parseFloat(document.getElementById("sugarsinput").value);
    portionsize = parseFloat(document.getElementById("portionSizeInput").value);
};
function calculatestats() {
    calories = (calories/100);
    fat = (fat/100);
    saturatedFat = (saturatedFat/100);
    salt = (salt/100);
    carbohydrates = (carbohydrates/100);
    sugars = (sugars/100);
};
function convertstats() {
    calories = (calories*portionsize);
    fat = (fat*portionsize);
    saturatedFat = (saturatedFat*portionsize);
    salt = (salt*portionsize);
    carbohydrates = (carbohydrates*portionsize);
    sugars = (sugars*portionsize);
}

function putstatsout(){
    document.getElementById("output1").innerHTML = ("calories:", calories);
    document.getElementById("output2").innerHTML = ("fat:", fat);
    document.getElementById("output3").innerHTML = ("saturated fat:", saturatedFat);
    document.getElementById("output4").innerHTML = ("salt:", salt);
    document.getElementById("output5").innerHTML = ("carbohydrates", carbohydrates);
    document.getElementById("output6").innerHTML = ("sugars:", sugars);
};
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <title>CALculator</title>
    <script src="script.js"></script>
</head>
<body>
    <div class="content">
        <h1>CALculator</h1>
        <sub>Please avoid using commas or dots.</sub>
        <p>Provide calorie intake for 100g:</p>
        <input id="caloriesinput" type="number"></input>
        <p>Enter fat content in 100g:</p>
        <input id="fatinput" type="number"></input>
        <p>Saturated fat in 100g:</p>
        <input id="saturatedFatinput" type="number"></input>
        <p>Salt amount in 100g:</p>
        <input id="saltinput" type="number"></input>
        <p>Carb content in 100g:</p>
        <input id="carbohydratesinput" type="number"></input>
        <p>Amount of sugars in 100g:</p>
        <input id="sugarsinput" type="number"></input>
        <hr>
        <p>Enter portion size in grams (or ml):</p>
        <input id="portionSizeInput" type="number"></input>
        <br>
        <br>
        <button onclick="getstats();calculatestats();convertstats();putstatsout();">Calculate</button>
        <h4>Results:</h4>
        <div style="display: flex; flex-direction: column;">
        <span class="output1">....</span>
        <span class="output2">....</span>
        <span class="output3">....</span>
        <span class="output4">....</span>
        <span class="output5">....</span>
        <span class="output6">....</span>          
        </div>
        
    </div>
</body>
</html>

Answer №1

@Keith i chose to use id's for each span because they needed unique outputs.

You have the option to use ID's or classes, but my point is that you are using classes for your span output like this:

<span class="output1">....</span>
, and then attempting to reference the element using an ID, which won't work if it doesn't have an ID assigned to it.

So, either utilize a query selector such as

document.querySelector('.output1')
or switch your outputs to have IDs instead, like this ->
<span id="output1">....</span>

Below is an example snippet that employs the querySelector approach.

Something must have changed in your code because it was working fine before.

No sudden stops usually occur without some changes being made. I suspect you may have switched from

<span id="output1">....</span>
to
<span class="output1">....</span>
, but forgot that you made this change.

var calories;
var fat;
var saturatedFat;
var salt;
var carbohydrates;
var sugars;
var portionsize;

function getstats() {
    calories = parseFloat(document.getElementById("caloriesinput").value);
    fat = parseFloat(document.getElementById("fatinput").value);
    saturatedFat = parseFloat(document.getElementById("saturatedFatinput").value);
    salt = parseFloat(document.getElementById("saltinput").value);
    carbohydrates = parseFloat(document.getElementById("carbohydratesinput").value);
    sugars = parseFloat(document.getElementById("sugarsinput").value);
    portionsize = parseFloat(document.getElementById("portionSizeInput").value);
};
function calculatestats() {
    calories = (calories/100);
    fat = (fat/100);
    saturatedFat = (saturatedFat/100);
    salt = (salt/100);
    carbohydrates = (carbohydrates/100);
    sugars = (sugars/100);
};
function convertstats() {
    calories = (calories*portionsize);
    fat = (fat*portionsize);
    saturatedFat = (saturatedFat*portionsize);
    salt = (salt*portionsize);
    carbohydrates = (carbohydrates*portionsize);
    sugars = (sugars*portionsize);
}

function putstatsout(){
    document.querySelector(".output1").innerHTML = ("calories:", calories);
    document.querySelector(".output2").innerHTML = ("fat:", fat);
    document.querySelector(".output3").innerHTML = ("saturated fat:", saturatedFat);
    document.querySelector(".output4").innerHTML = ("salt:", salt);
    document.querySelector(".output5").innerHTML = ("carbohydrates", carbohydrates);
    document.querySelector(".output6").innerHTML = ("sugars:", sugars);
};
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <title>CALculator</title>
    <script src="script.js"></script>
</head>
<body>
    <div class="content">
        <h1>CALculator</h1>
        <sub>Please enter values without commas or dots.</sub>
        <p>Calories in 100g:</p>
        <input id="caloriesinput" type="number"></input>
        <p>Fat in 100g:</p>
        <input id="fatinput" type="number"></input>
        <p>Saturated Fat in 100g:</p>
        <input id="saturatedFatinput" type="number"></input>
        <p>Salt in 100g:</p>
        <input id="saltinput" type="number"></input>
        <p>Carbohydrates in 100g:</p>
        <input id="carbohydratesinput" type="number"></input>
        <p>Sugars in 100g:</p>
        <input id="sugarsinput" type="number"></input>
        <hr>
        <p>What is the portion size (in grams/ml)?</p>
        <input id="portionSizeInput" type="number"></input>
        <br>
        <br>
        <button onclick="getstats();calculatestats();convertstats();putstatsout();">Calculate</button>
        <h4>Results:</h4>
        <div style="display: flex; flex-direction: column;">
        <span class="output1">....</span>
        <span class="output2">....</span>
        <span class="output3">....</span>
        <span class="output4">....</span>
        <span class="output5">....</span>
        <span class="output6">....</span>          
        </div>
        
    </div>
</body>
</html>

Answer №2

Consider implementing Bharat's suggestion. You could also experiment with the following approach:

window.onload = () => {
    // insert your code here
}

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

Can you explain the significance of the characters '& > * + *' in JSX (CSS)?

When using material UI, the progressbar demo includes lines of JSX code like this: '& > * + *': { marginTop: theme.spacing(2), }, Can you explain what the selector '& > * + *' represents in this context? ...

Is your Bootstrap input displaying the has-error class with a glyphicon, but the alignment is not vertically centered?

What is the reason for the misalignment of glyphicon-warning-sign form-control-feedback vertically in the code below after applying font-size: 20px; to the label? <div class="container"> <div class="content align-left contact"> ...

Implementing relative path 'fetch' in NextJs App Router

When attempting to retrieve data using fetch("/api/status"), the URL is only detected when utilizing the absolute path: fetch("http://localhost:3000/api/status"). This is happening without storing the path in a variable. ...

"Include the 'unsafe' prefix at the start of the URL in AngularJS

Whenever I attempt to access app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 within my app, the URL gets parsed as ==> unsafe:app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 Is ...

What is the best way to create a JavaScript Up/Down Numeric input box using jQuery?

So, I have this Numeric input box with Up/Down buttons: HTML Markup: <div class="rotatortextbox"> <asp:TextBox ID="txtrunningtimeforfirstlot" ClientIDMode="Static" runat="server">0</asp:TextBox> (In mins) </div> <div cl ...

Best practices for declaring variables in ReactJS

I need help understanding how to declare a variable in a React JS class so that it is accessible in different functions. Here is my code snippet: class MyContainer extends Component { constructor(props) { super(props); this.testVariable ...

Generating hills with PlaneGeometry in Three.js

Currently, I am searching for a straightforward technique to generate non-uniform hills in Three.js. By utilizing particles and positioning them with a sine wave algorithm like the following snippet: x = Math.random() * 1000 y = Math.sin( x / freq ) * ...

When implementing AngularJS in a situation where the page layout is created by the user, what is the best

As I work on developing a web application, my main goal is to incorporate around 6 unique "widgets" that users can interact with. These widgets will serve different functions and users will have the ability to add, remove, and position them as they wish on ...

Include a new feature within an onClick event

I'm looking to implement a single page application using React.js and I want to incorporate a list within a material-ui drawer. The goal is to dynamically add elements to an array every time a button is clicked, but I'm stuck on how to write this ...

code, scripting - modal pop-up

My script currently has a popup window using window.open, but most browsers block this type of popups. I now want to change it to another popup that includes a php script, similar to what I've seen on other sites. It seems like they are using ajax. Ca ...

Reacting with Angulatory: Response heads are not being transferred in applications

I'm facing an issue where the cookie containing my authentication token doesn't get passed along with my requests. After authenticating in Chrome, the response sets the cookie correctly, but it's not included in subsequent requests. This is ...

When utilizing Express and passport, an error occurs stating that req.isAuthenticated is undefined

After successfully setting up a backend express server in the past few hours, I decided to implement authorization by following a tutorial. The login functionality works perfectly, but when attempting to access /authrequired (a restricted page that require ...

Customize the Hidden Footer in Wordpress

I have a question about the footer code in my theme. I want to remove the "Powered by WordPress" text, but I can't seem to find the solution here. Can someone please help me with this? <?php do_action( 'maxwell_before_footer' ); ?> & ...

Harnessing the power of jQuery to create a horizontal scrolling experience based

I'm working on creating a javascript version of the website that currently uses flash. So far, I have completed the basic layout, which consists of a simple horizontal container with divs. You can view the code here http://pastebin.com/U3z2aJve I a ...

Who is the intended audience for the "engines" field in an npm package - consumers or developers?

As the creator of an npm library, I have included the current LTS versions of Node.js and npm in the package manifest under the engines field. This ensures that all contributors use the same versions I utilized for development: Node.js <a href="/cdn-cgi ...

Retrieve a true value by using either Array.some or _.some

I am looking to retrieve a truthy value from the array.Some other than "true", This is my approach: let category; arduair.aqi_ranges[pollutant].some((item,index)=> { let min = item.range[0]; let max = item.range[1]; if (_.inRange(c,min,max)){ ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

Issue with scrolling in Droppable container on JQuery UI interface

I've encountered an issue with JQuery UI. In my code snippet, I can drag elements onto fields and when hovering over a field, it gets highlighted in green. However, I recently added the functionality to scroll while dragging. Now, I can scroll up and ...

The height set to 100% is causing issues with the padding-bottom property

Currently, I have a setup that includes: A div with width set to 100% and height set to 100% An SVG element inside the div with default width and height of 100% My issue is that when applying padding to the div, the left, right, and top padding seem to w ...

setting the child div's margin in relation to its parent div

Here is my HTML: <div class='mainDiv'> <div class='subDiv'></div> </div> This is the corresponding CSS code: .mainDiv { margin-top: 200px; width: 700px; height: 800px; background-color: red ...