0

I have to build a calculator using only JS, no HTML. I'm creating the basic input fields for the numbers, but I can't seem to append them to the DOM. I get the following error:

> Uncaught TypeError: Cannot read property 'append' of null.

This is my code:

var firstInput = document.createElement('input');
firstInput.setAttribute("type", "text");
firstInput.innerHTML = "";
document.body.append(firstInput);

CLARIFICATION: There is an HTML file, and I'm working on an external Javascript file that's linked to the HTML. However, they won't let me create elements from HTML and get them with Javascript. I can only create Elements using JS.

What am I doing wrong?

Vinyet
  • 9
  • 4
  • I'm going to guess that your code is in the `` without being wrapped in an `onload`, thus you're trying to access the `` before it exists. – Tyler Roper Nov 19 '19 at 20:13
  • Possible duplicate of [Why is document.body null in my javascript?](https://stackoverflow.com/questions/9916747/why-is-document-body-null-in-my-javascript) – norbitrial Nov 19 '19 at 20:14
  • 2
    Using "the DOM" with "no HTML" is doesn't make sense. The DOM is a tool for using JavaScript to access, navigate, and alter the HTML. Without HTML, there is no DOM. – Andrew Ray Nov 19 '19 at 20:16
  • @AndrewRay I would imagine that OP means they are using solely JS to construct the page elements, as opposed to the page "not being HTML". That said, we shouldn't have to guess, so your point brings to light that the question could certainly use some clarification. – Tyler Roper Nov 19 '19 at 20:17
  • @TylerRoper, right then, not sure why you would want to do that, but I guess it's just another homework assignment that does a terrible job approximating anything resembling the real world. I was thinking we were dealing with Node or similar "headless" JS. – Andrew Ray Nov 19 '19 at 20:22

1 Answers1

1

When your code is executed, the body is not necessarily loaded yet. It is a good practice to wait for the DOM to be ready before using it in any way.

Your script should be placed at the very end of the HTML body.

(function() {
  // The DOM will be available here
  var firstInput = document.createElement('input');
  firstInput.setAttribute("type", "text");
  firstInput.innerHTML = "";
  document.body.append(firstInput);
})();

This answer gives you more details on how it works.

SystemGlitch
  • 1,790
  • 9
  • 25
  • 1
    The key point is that the script tags with the snippet above are placed just before the body end tag (

    ) and after all the other html markup.

    – T. Junghans Nov 19 '19 at 20:28