0

I apologize if this is a really dumb question but its driving me crazy. When posting this question there were duplicate questions but the answer that the element "section" in my case does not exist is not valid because the element exists.

    <script>
    for(var i=0; i < 45;i++) {
        var div = document.createElement("div");
        div.onClick = function() {
            alert("you clicked on a box #" + i);
        };

        document.getElementsByTagName('section')[0].appendChild(div);
    }



    </script>
    <title>Let Keyword</title>


</head>
<body>
    <header>
        <h1>Click on a box</h1>
    </header>
     <section></section>
</body> 
</html>
  • 1
    Well it does really not exist when you call the function. Not yet. – Bergi Sep 07 '17 at 01:59
  • 1
    onclick should be all lower case https://www.w3schools.com/jsref/event_onclick.asp – Bindrid Sep 07 '17 at 02:11
  • This may or may not be a duplicate - but - @Bindrid is right, the onclick event handler should be all lowercase, not onClick. Tested in a jsfiddle: https://jsfiddle.net/wrv369/kyf0v900/1/. Also notice the subtle difference in the for loop; changed var to let. – iCode Sep 07 '17 at 02:42

0 Answers0