0

So I am creating JSON objects for certain incomes and expenses. I have added names, amounts and if recurring or not.

However Im trying to print values from these objects to a div element by using a for loop. I have tried getting the div by getElementById and then using innerHtml to print the values of the object but I get this error:

Uncaught TypeError: Cannot read properties of null (reading 'innerHTML')

Below is my javascript:

const incomes = [
  {
    name: "Walter",
    amount: 2000,
    recurring: true,
  },
  {
    name: "James",
    amount: 4000,
    recurring: true,
  },
  {
    name: "Mike",
    amount: 500,
    recurring: true,
  },
  {
    name: "Jane",
    amount: 1000,
    recurring: true,
  },
  {
    name: "Larry",
    amount: 5000,
    recurring: true,
  },
];

for (i = 0; i < incomes.length; i++) {
  let container = document.getElementById("container");
  container.innerHTML(expenses[i].name);
}

const expenses = [
  {
    name: "Electricity",
    amount: 700,
    recurring: true,
  },
  {
    name: "Water",
    amount: 500,
    recurring: true,
  },
  {
    name: "Internet",
    amount: 800,
    recurring: true,
  },
  {
    name: "Rent",
    amount: 7500,
    recurring: true,
  },
  {
    name: "Transport",
    amount: 1500,
    recurring: true,
  },
];

for (i = 0; i < expenses.length; i++) {
  let container = document.getElementById("container");
  container.innerHTML(expenses[i].name);
}

And my HTML too:

<!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" />
    <title>Incomes and Expenses</title>
    <script src="incomes.js"></script>
    <link rel="stylesheet" href="incomes.css" />
  </head>
  <body>
    <h1 class="income">Incomes</h1>

    <div id="container" class="container"></div>

  </body>
</html>

Thank you

  • There are many things wrong in your code,1. `container.innerHTML(expenses[i].name)` is wrong,because **`innerHTML` is not a function**,if you want to join and set value then use `container.innerHTML+=expenses[i].name+' '`,2. `const expenses` should be declared after `const incomes` and **before all for loops**,I don't know why they have closed this questions,but anyway,have you got answer from the link they gave(as a proof for closing)? – Neptotech -vishnu Mar 10 '22 at 10:36

1 Answers1

0

You probably want to execute your javascript commands after the html is loaded. Try moving it before closing of the <body> tag (see below). Right now, it executes before your container element is created in the DOM.

      ...

      <script src="incomes.js"></script>
   </body>
</html>
entio
  • 3,816
  • 1
  • 24
  • 39