Vinyet
Vinyet

Reputation: 31

Can't append inputs to the DOM

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?

Upvotes: 0

Views: 283

Answers (1)

SystemGlitch
SystemGlitch

Reputation: 2262

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.

Upvotes: 1

Related Questions