1

I am struggling with a little javascript.

I have these four lines:

var footer = document.getElementById('footer');
var cookieBanner = document.createElement('div');
cookiebanner.className = "cookieBanner";
footer.appendChild(cookiebanner);

But in console I get

Uncaught TypeError: Cannot read property 'appendChild' of undefined

If I do the same in console, it works. Why would that be?

akmur
  • 1,185
  • 1
  • 18
  • 35

1 Answers1

4

var footer = document.getElementById('footer'); is returning undefined. Therefore when you try and call appendChild on undefined, you get:

Uncaught TypeError: Cannot read property 'appendChild' of undefined

If there is an element with that ID on your page, make sure your page is being rendered before this script is being ran.

tymeJV
  • 99,730
  • 13
  • 150
  • 152