简体   繁体   中英

BEGINNER JavaScript creating elements

I am currently working on creating elements via Java Script. For practice I am trying to populate an already existing 'form' element with a button, however I am receiving the following error;

Uncaught TypeError: Cannot read property 'appendChild' of null

<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  </head>
  <body>    
    <form></form>
  </body>
  <script type="text/javascript">
    var btn = document.createElement('BUTTON');
    var txt = document.createTextNode('CLICK ME');
    btn.appendChild(txt);

    document.getElementById('#form').appendChild(btn);
  </script>
</html>

You did not assign your <form> element an ID of form .

<body>  
    <form id="form">

    </form>
</body>

You also don't need a # when using getElementById() .

document.getElementById('form').appendChild(btn);

If you don't want to assign an ID, you can use getElementsByTagName :

document.getElementsByTagName('form')[0].appendChild(btn);
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>  
        <form id="f">
        </form>
        <script type="text/javascript">
            var btn = document.createElement('BUTTON');
            var txt = document.createTextNode('CLICK ME');
            btn.appendChild(txt);
            document.getElementById("f").appendChild(btn);
        </script>
    </body>
</html>
  • <script> should either be inside the <head> or <body> .

  • You didn't set an id for <form> . Otherwise you can use getElementsByTagName() .

Ex:

document.getElementsByTagName('form')[0].appendChild(btn);

1. <script> cannot be outside outside of <body>

  1. You've not given your form an id .

  2. AND you don't need # because it's CSS syntax for ids and the method already knows you are providing it an id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM