0

I'm working on my HTML & JavaScript project.

When I run my code, I have an error which is

"Cannot read property 'appendChild' of null".

I tried to solve this problem, and I found here, but I can't understand because I'm beginner of programming, and I'm not good at English.

Here's my code:

<html>
<head>
    <script language="javascript">
        var wordlist = [ "a", "bb", "ccc", "dddd" ];
        var rannum = Math.floor(Math.random() * wordlist.length);
        var x = document.createElement("INPUT");

        for(i = 0; i < wordlist[rannum].length; i++) {
            x.setAttribute("type", "text");
            x.setAttribute("value", "");
            document.body.appendChild(x);
        }

    </script>
</head>
<body>
</body>
</html>

Could you help me to solve the problem?

Thank you in advance.

Mamun
  • 66,969
  • 9
  • 47
  • 59
Hoseong Jeon
  • 1,240
  • 2
  • 12
  • 20

1 Answers1

3

Your script is running before the DOM is fully loaded. There several ways to fix the issue:

  1. You can specify defer attribute in the script tag.
  2. You can wrap the code with DOMContentLoaded event which is fired when the initial HTML document has been completely loaded and parsed.
  3. You can place the script at the end of the body.

Attribute defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

By creating the input outside the loop you are referencing the same element in each iteration in the loop. You have to create the element inside the loop

<html>
<head>
    <script language="javascript" defer>
        var wordlist = [ "a", "bb", "ccc", "dddd" ];
        var rannum = Math.floor(Math.random() * wordlist.length);
        for(i = 0; i < wordlist[rannum].length; i++) {
            var x = document.createElement("INPUT");
            x.setAttribute("type", "text");
            x.setAttribute("value", "");
            document.body.appendChild(x);
        }

    </script>
</head>
<body>
</body>
</html>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • Thank you. But it doesn't work when I copy your code, paste it, and run my code. It works on snippet, But it doesn't work on my code. I don't know what the problem is. – Hoseong Jeon Nov 11 '18 at 04:47
  • @HoseongJeon, as we are unable to see your actual code, we can not do much. We can only try to find the solution based on the code you have posted here......thanks. – Mamun Nov 11 '18 at 04:50
  • @HoseongJeon, by noticing the comment, I have updated the answer....please check – Mamun Nov 11 '18 at 04:55
  • @HoseongJeon, you are most welcome....:) – Mamun Nov 11 '18 at 04:59