-1

I have an Array of text, that generates Buttons(see in the Code example) and the generated Buttons should then be added to a div and not to the body.

Javascript

    <script>
        //let list = ["A","B","C"];
        let list = JSON.parse(localStorage.getItem("PrüfungenName"));
        let listBtns = [];
        let listPs = [];
            for (let i = 0; i < list.length; ++i) {
                var button = document.createElement("button");
                var p = document.createElement("p");
                p.innerHTML = "nicht durchgeführt";
                p.id = "p " + i;

                button.innerHTML = list[i];
                button.name = list[i];
                button.id = "Button " + i;

                button.labels = list[i];
                listBtns[i] = button;

                listPs[i] = p;
                button.addEventListener("click", OpenAndLoad());
                document.getElementById("AddedButtons").appendChild(button);
                document.getElementById("AddedButtons").appendChild(p);
            }
    </script>

    <div id="AddedButtons"></div>

Error Message

Uncaught TypeError: Cannot read property 'appendChild' of null at ""

When trying document.body.appenChild(button) it works, but thats not what I want.

Jaydeep
  • 1,686
  • 1
  • 16
  • 29

1 Answers1

1

Put you script after the div. The div will not be present at the time yoir script is executed. Alternatively add a funtion around your script that executes when the dom is ready.

niklas
  • 2,887
  • 3
  • 38
  • 70