Y Zhu
Y Zhu

Reputation: 43

How to Fix JavaScript HTML Element Did Not Show an Error?

TypeScript code is as follows:

namespacesLab.ts:

var ArrayUtilities;
(function (ArrayUtilities) {
    function reverseArray(array) {
        return array.slice(0).reverse();
    }
    ArrayUtilities.reverseArray = reverseArray;
    function lastItemOfArray(array) {
        return array.slice(0).pop();
    }
    ArrayUtilities.lastItemOfArray = lastItemOfArray;
    function firstItemOfArray(array) {
        return array.slice(0).shift();
    }
    ArrayUtilities.firstItemOfArray = firstItemOfArray;
    function concatenateArray(array1, array2) {
        return array1.concat(array2);
    }
    ArrayUtilities.concatenateArray = concatenateArray;
})(ArrayUtilities || (ArrayUtilities = {}));

HTML code is as follows:

index.html:

<script src="namespacesLab.js"></script>
<html>
  <body>
    <script>
      array1 = [1, 2, 3, 4, 5];
      array2 = [6, 7, 8, 9, 10];

      function callArrayUtil(util, array, array2 = null) {
        document.getElementById("output").innerHTML = ArrayUtilities[util](
          array,
          array2
        ).toString();
      }
      document.getElementById("output").innerHTML = array1.toString();
    </script>

    <div id="output " style="width:100%;"></div>
    <button onclick="callArrayUtil('reverseArray', array1)">
      Reverse Array
    </button>
    <button onclick="callArrayUtil('lastItemOfArray', array1)">
      Last Item of Array
    </button>
    <button onclick="callArrayUtil('firstItemOfArray', array1)">
      First Item of Array
    </button>
    <button onclick="callArrayUtil('concatenateArray', array1, array2)">
      Concatenate Array
    </button>
  </body>
</html>

When I click the index.html, a webpage showing four buttons appears. However, there is no array displayed.

expected result: four buttons and an array shown on the webpage

actual result: the array did not show on the webpage

Upvotes: 3

Views: 364

Answers (2)

slappydappy
slappydappy

Reputation: 56

After running your code, it looks like your issue is your div id:

<div id = "output " style = "width:100%;">

Your id has an extra whitespace and you are looking for:

document.getElementById("output")

It looks like you might also have some issues accessing the DOM before it has been constructed. Take a look at this answer for some more info.

Some extra tips for you: For pretty much every major web browser available, there are web developer tools that can greatly help you debug your web apps/pages. Chrome developer tools, for example, can be accessed using Ctrl+Shift+I or simply right click>>Inspect.

Upvotes: 2

imvain2
imvain2

Reputation: 15847

you have a space in your ID:

change

<div id = "output " style = "width:100%;">

to

<div id = "output" style = "width:100%;">

Upvotes: 4

Related Questions