0

for my toast notifications I create a div container called "toastArea". So when I write in my HTML file

<div class="toastArea"></div>

everything is fine. But I want to create it dynamically by using JS. So in my toast controller I write

class ToastController { // class for toast notifications
  constructor() {
    this.CreateToastArea(); // create a div for every toasts
  }

    CreateToastArea() {
      var area = document.createElement("div"); // create div
      area.classList.add("toastArea"); // add a class to the div
      document.body.appendChild(area); // append div to the body
    }
}

but when the constructor calls the function it says

Cannot read property 'appendChild' of null

but the variable "area" is not null. The div got created correctly.

I don't get what's wrong there..

Question3r
  • 2,166
  • 19
  • 100
  • 200
  • Please create a [mcve]. Don Rhummy's answer sounds plausible, but you haven't included enough information to verify that it's the cause. Where are you calling `new ToastController()`? – 4castle May 09 '17 at 17:52
  • Possible duplicate of [Why is document.body null in my javascript?](http://stackoverflow.com/questions/9916747/why-is-document-body-null-in-my-javascript) – 4castle May 09 '17 at 19:37

1 Answers1

1

Your script is loaded in the header. You need to tie the instantiation of your ToastController to the loading/parsing of the body.

For example, in jQuery:

jQuery( document ).ready( function() { window.myToastController = new ToastController(); } );
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
  • If you have to use your crystal ball in order to answer a question, it's much better if you ask for clarification from the asker first. You shouldn't need to assume information that isn't in the question in order to write an answer. – 4castle May 09 '17 at 17:57
  • well that worked :) In my html file I used `` and that was fine. In this function I created my controller, thank you :) – Question3r May 09 '17 at 18:18
  • @4castle While I agree that it should have been stated in the question, after years of experience, it's a lot easier to spot the main causes of common errors. – Don Rhummy May 09 '17 at 19:36
  • @DonRhummy If it's a common error, it's likely a duplicate question. I've marked one, which you may decide to vote on. – 4castle May 09 '17 at 19:38