Rami Awar
Rami Awar

Reputation: 760

Uncaught Type Error for creating an empty div in JS

So what I have is a script to generate snowflakes and everything was working fine. I'm going for raw javascript here. No jquery whatsoever. So I want to just throw the script in and it creates its own classes and assigns them without a previously made style-sheet. So I create the element and then try to append it to the body, but it says the element is null.

...

<script>
  this.elem = document.createElement('div');
  document.getElementById('body').appendChild(this.elem);                           //appending flake to body
</script>

...

this gives an error.

Upvotes: 0

Views: 395

Answers (2)

Aamir Shahzad
Aamir Shahzad

Reputation: 6834

You can achieve it by changing your HTML markup to this;

<body id="body">
</body>

Same code will work fine.

Working Fiddle

If you don't want to change HTML markup you can achieve it by getElementsByTagName as answered by @Bhojendra

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

You need to use getElementsByTagName:

document.getElementsByTagName('body')[0].appendChild(this.elem);

if you're trying to append inside <body></body>

Upvotes: 2

Related Questions