Create Button Element in JavaScript











up vote
1
down vote

favorite












I'm trying to create a button element in javascript without using jQuery.



I keep getting an error when I try to append it to the DOM.




"Cannot read property 'appendChild' of null"




I've looked everywhere and couldn't find out how to create a button. In the w3Schools example they are using a function on a button element that was already created in the HTML, which isn't what I'm trying to do. Here's what I have.



HTML:



<!DOCTYPE html> 
<html lang="en">
<head>
meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="myapp.js"></script>
</head>
<body>
<div id="btn">Button Here</div>
</body>
</html>


myapp.js



var element = document.createElement("button");
element.appendChild(document.createTextNode("Click Me!"));
var page = document.getElementById("btn");
page.appendChild(element);
console.log(element);









share|improve this question
























  • Looks like #btn doesn't exist.
    – CertainPerformance
    Jun 24 at 2:47










  • it exists as a div in my html
    – kmulqueen
    Jun 24 at 2:48












  • Doesn't look like it does, at least not at the time the script runs, else it wouldn't be null
    – CertainPerformance
    Jun 24 at 2:50












  • It is hard to help you without seeing your HTML and the JS in action. Please create a Minimal, Complete, and Verifiable example.
    – Victoria Ruiz
    Jun 24 at 2:51










  • so I have a div inside of my html with the id "btn". I'm trying to create a button element in javascript and append that button to the div with the id of button. I know this sounds stupid... I'm just trying to practice and get familiar with javascript.
    – kmulqueen
    Jun 24 at 2:52















up vote
1
down vote

favorite












I'm trying to create a button element in javascript without using jQuery.



I keep getting an error when I try to append it to the DOM.




"Cannot read property 'appendChild' of null"




I've looked everywhere and couldn't find out how to create a button. In the w3Schools example they are using a function on a button element that was already created in the HTML, which isn't what I'm trying to do. Here's what I have.



HTML:



<!DOCTYPE html> 
<html lang="en">
<head>
meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="myapp.js"></script>
</head>
<body>
<div id="btn">Button Here</div>
</body>
</html>


myapp.js



var element = document.createElement("button");
element.appendChild(document.createTextNode("Click Me!"));
var page = document.getElementById("btn");
page.appendChild(element);
console.log(element);









share|improve this question
























  • Looks like #btn doesn't exist.
    – CertainPerformance
    Jun 24 at 2:47










  • it exists as a div in my html
    – kmulqueen
    Jun 24 at 2:48












  • Doesn't look like it does, at least not at the time the script runs, else it wouldn't be null
    – CertainPerformance
    Jun 24 at 2:50












  • It is hard to help you without seeing your HTML and the JS in action. Please create a Minimal, Complete, and Verifiable example.
    – Victoria Ruiz
    Jun 24 at 2:51










  • so I have a div inside of my html with the id "btn". I'm trying to create a button element in javascript and append that button to the div with the id of button. I know this sounds stupid... I'm just trying to practice and get familiar with javascript.
    – kmulqueen
    Jun 24 at 2:52













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I'm trying to create a button element in javascript without using jQuery.



I keep getting an error when I try to append it to the DOM.




"Cannot read property 'appendChild' of null"




I've looked everywhere and couldn't find out how to create a button. In the w3Schools example they are using a function on a button element that was already created in the HTML, which isn't what I'm trying to do. Here's what I have.



HTML:



<!DOCTYPE html> 
<html lang="en">
<head>
meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="myapp.js"></script>
</head>
<body>
<div id="btn">Button Here</div>
</body>
</html>


myapp.js



var element = document.createElement("button");
element.appendChild(document.createTextNode("Click Me!"));
var page = document.getElementById("btn");
page.appendChild(element);
console.log(element);









share|improve this question















I'm trying to create a button element in javascript without using jQuery.



I keep getting an error when I try to append it to the DOM.




"Cannot read property 'appendChild' of null"




I've looked everywhere and couldn't find out how to create a button. In the w3Schools example they are using a function on a button element that was already created in the HTML, which isn't what I'm trying to do. Here's what I have.



HTML:



<!DOCTYPE html> 
<html lang="en">
<head>
meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="myapp.js"></script>
</head>
<body>
<div id="btn">Button Here</div>
</body>
</html>


myapp.js



var element = document.createElement("button");
element.appendChild(document.createTextNode("Click Me!"));
var page = document.getElementById("btn");
page.appendChild(element);
console.log(element);






javascript html button element createelement






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 24 at 2:57









NewToJS

2,3493919




2,3493919










asked Jun 24 at 2:46









kmulqueen

142




142












  • Looks like #btn doesn't exist.
    – CertainPerformance
    Jun 24 at 2:47










  • it exists as a div in my html
    – kmulqueen
    Jun 24 at 2:48












  • Doesn't look like it does, at least not at the time the script runs, else it wouldn't be null
    – CertainPerformance
    Jun 24 at 2:50












  • It is hard to help you without seeing your HTML and the JS in action. Please create a Minimal, Complete, and Verifiable example.
    – Victoria Ruiz
    Jun 24 at 2:51










  • so I have a div inside of my html with the id "btn". I'm trying to create a button element in javascript and append that button to the div with the id of button. I know this sounds stupid... I'm just trying to practice and get familiar with javascript.
    – kmulqueen
    Jun 24 at 2:52


















  • Looks like #btn doesn't exist.
    – CertainPerformance
    Jun 24 at 2:47










  • it exists as a div in my html
    – kmulqueen
    Jun 24 at 2:48












  • Doesn't look like it does, at least not at the time the script runs, else it wouldn't be null
    – CertainPerformance
    Jun 24 at 2:50












  • It is hard to help you without seeing your HTML and the JS in action. Please create a Minimal, Complete, and Verifiable example.
    – Victoria Ruiz
    Jun 24 at 2:51










  • so I have a div inside of my html with the id "btn". I'm trying to create a button element in javascript and append that button to the div with the id of button. I know this sounds stupid... I'm just trying to practice and get familiar with javascript.
    – kmulqueen
    Jun 24 at 2:52
















Looks like #btn doesn't exist.
– CertainPerformance
Jun 24 at 2:47




Looks like #btn doesn't exist.
– CertainPerformance
Jun 24 at 2:47












it exists as a div in my html
– kmulqueen
Jun 24 at 2:48






it exists as a div in my html
– kmulqueen
Jun 24 at 2:48














Doesn't look like it does, at least not at the time the script runs, else it wouldn't be null
– CertainPerformance
Jun 24 at 2:50






Doesn't look like it does, at least not at the time the script runs, else it wouldn't be null
– CertainPerformance
Jun 24 at 2:50














It is hard to help you without seeing your HTML and the JS in action. Please create a Minimal, Complete, and Verifiable example.
– Victoria Ruiz
Jun 24 at 2:51




It is hard to help you without seeing your HTML and the JS in action. Please create a Minimal, Complete, and Verifiable example.
– Victoria Ruiz
Jun 24 at 2:51












so I have a div inside of my html with the id "btn". I'm trying to create a button element in javascript and append that button to the div with the id of button. I know this sounds stupid... I'm just trying to practice and get familiar with javascript.
– kmulqueen
Jun 24 at 2:52




so I have a div inside of my html with the id "btn". I'm trying to create a button element in javascript and append that button to the div with the id of button. I know this sounds stupid... I'm just trying to practice and get familiar with javascript.
– kmulqueen
Jun 24 at 2:52












4 Answers
4






active

oldest

votes

















up vote
3
down vote













Your script is running before the DOM has finished loading, so before your 'btn' div exists. There are a few simple solutions to this. One is moving your script tag to the bottom of the body, eg:



<!DOCTYPE html> 
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="btn">Button Here</div>
<script src="myapp.js"></script>
</body>
</html>


The other, better, solution is adding a line to your script to make sure the HTML has loaded before the script runs.



document.addEventListener("DOMContentLoaded", function() {
var element = document.createElement("button");
element.appendChild(document.createTextNode("Click Me!"));
var page = document.getElementById("btn");
page.appendChild(element);
console.log(element);
});


//Corected "meta charset="UTF-8"".






share|improve this answer






























    up vote
    0
    down vote













    It's likely that page is the object that is undefined. Here's a fiddle with a working example:



    https://jsfiddle.net/2Lon63uj/






    share|improve this answer




























      up vote
      0
      down vote













      Working demo here






      function createButton() {
      var element = document.createElement("button");
      element.appendChild(document.createTextNode("Click Me!"));
      var page = document.getElementById("btn");
      page.appendChild(element);

      console.log(element);
      }

      createButton();

      <div id="btn">
      </div>








      share|improve this answer






























        up vote
        0
        down vote













        Are you sure your HTML file can see your script. Why not try running small tests on the console window. View of the output of those elements and see if it gives null.






        share|improve this answer





















          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51006577%2fcreate-button-element-in-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote













          Your script is running before the DOM has finished loading, so before your 'btn' div exists. There are a few simple solutions to this. One is moving your script tag to the bottom of the body, eg:



          <!DOCTYPE html> 
          <html lang="en">
          <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>Document</title>
          </head>
          <body>
          <div id="btn">Button Here</div>
          <script src="myapp.js"></script>
          </body>
          </html>


          The other, better, solution is adding a line to your script to make sure the HTML has loaded before the script runs.



          document.addEventListener("DOMContentLoaded", function() {
          var element = document.createElement("button");
          element.appendChild(document.createTextNode("Click Me!"));
          var page = document.getElementById("btn");
          page.appendChild(element);
          console.log(element);
          });


          //Corected "meta charset="UTF-8"".






          share|improve this answer



























            up vote
            3
            down vote













            Your script is running before the DOM has finished loading, so before your 'btn' div exists. There are a few simple solutions to this. One is moving your script tag to the bottom of the body, eg:



            <!DOCTYPE html> 
            <html lang="en">
            <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
            </head>
            <body>
            <div id="btn">Button Here</div>
            <script src="myapp.js"></script>
            </body>
            </html>


            The other, better, solution is adding a line to your script to make sure the HTML has loaded before the script runs.



            document.addEventListener("DOMContentLoaded", function() {
            var element = document.createElement("button");
            element.appendChild(document.createTextNode("Click Me!"));
            var page = document.getElementById("btn");
            page.appendChild(element);
            console.log(element);
            });


            //Corected "meta charset="UTF-8"".






            share|improve this answer

























              up vote
              3
              down vote










              up vote
              3
              down vote









              Your script is running before the DOM has finished loading, so before your 'btn' div exists. There are a few simple solutions to this. One is moving your script tag to the bottom of the body, eg:



              <!DOCTYPE html> 
              <html lang="en">
              <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <meta http-equiv="X-UA-Compatible" content="ie=edge">
              <title>Document</title>
              </head>
              <body>
              <div id="btn">Button Here</div>
              <script src="myapp.js"></script>
              </body>
              </html>


              The other, better, solution is adding a line to your script to make sure the HTML has loaded before the script runs.



              document.addEventListener("DOMContentLoaded", function() {
              var element = document.createElement("button");
              element.appendChild(document.createTextNode("Click Me!"));
              var page = document.getElementById("btn");
              page.appendChild(element);
              console.log(element);
              });


              //Corected "meta charset="UTF-8"".






              share|improve this answer














              Your script is running before the DOM has finished loading, so before your 'btn' div exists. There are a few simple solutions to this. One is moving your script tag to the bottom of the body, eg:



              <!DOCTYPE html> 
              <html lang="en">
              <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <meta http-equiv="X-UA-Compatible" content="ie=edge">
              <title>Document</title>
              </head>
              <body>
              <div id="btn">Button Here</div>
              <script src="myapp.js"></script>
              </body>
              </html>


              The other, better, solution is adding a line to your script to make sure the HTML has loaded before the script runs.



              document.addEventListener("DOMContentLoaded", function() {
              var element = document.createElement("button");
              element.appendChild(document.createTextNode("Click Me!"));
              var page = document.getElementById("btn");
              page.appendChild(element);
              console.log(element);
              });


              //Corected "meta charset="UTF-8"".







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 19 at 19:59









              Radu Sologub

              31




              31










              answered Jun 24 at 3:21









              n-a-t-e

              313




              313
























                  up vote
                  0
                  down vote













                  It's likely that page is the object that is undefined. Here's a fiddle with a working example:



                  https://jsfiddle.net/2Lon63uj/






                  share|improve this answer

























                    up vote
                    0
                    down vote













                    It's likely that page is the object that is undefined. Here's a fiddle with a working example:



                    https://jsfiddle.net/2Lon63uj/






                    share|improve this answer























                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      It's likely that page is the object that is undefined. Here's a fiddle with a working example:



                      https://jsfiddle.net/2Lon63uj/






                      share|improve this answer












                      It's likely that page is the object that is undefined. Here's a fiddle with a working example:



                      https://jsfiddle.net/2Lon63uj/







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jun 24 at 2:52









                      GrokSrc

                      1,5061522




                      1,5061522






















                          up vote
                          0
                          down vote













                          Working demo here






                          function createButton() {
                          var element = document.createElement("button");
                          element.appendChild(document.createTextNode("Click Me!"));
                          var page = document.getElementById("btn");
                          page.appendChild(element);

                          console.log(element);
                          }

                          createButton();

                          <div id="btn">
                          </div>








                          share|improve this answer



























                            up vote
                            0
                            down vote













                            Working demo here






                            function createButton() {
                            var element = document.createElement("button");
                            element.appendChild(document.createTextNode("Click Me!"));
                            var page = document.getElementById("btn");
                            page.appendChild(element);

                            console.log(element);
                            }

                            createButton();

                            <div id="btn">
                            </div>








                            share|improve this answer

























                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









                              Working demo here






                              function createButton() {
                              var element = document.createElement("button");
                              element.appendChild(document.createTextNode("Click Me!"));
                              var page = document.getElementById("btn");
                              page.appendChild(element);

                              console.log(element);
                              }

                              createButton();

                              <div id="btn">
                              </div>








                              share|improve this answer














                              Working demo here






                              function createButton() {
                              var element = document.createElement("button");
                              element.appendChild(document.createTextNode("Click Me!"));
                              var page = document.getElementById("btn");
                              page.appendChild(element);

                              console.log(element);
                              }

                              createButton();

                              <div id="btn">
                              </div>








                              function createButton() {
                              var element = document.createElement("button");
                              element.appendChild(document.createTextNode("Click Me!"));
                              var page = document.getElementById("btn");
                              page.appendChild(element);

                              console.log(element);
                              }

                              createButton();

                              <div id="btn">
                              </div>





                              function createButton() {
                              var element = document.createElement("button");
                              element.appendChild(document.createTextNode("Click Me!"));
                              var page = document.getElementById("btn");
                              page.appendChild(element);

                              console.log(element);
                              }

                              createButton();

                              <div id="btn">
                              </div>






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jun 24 at 2:57

























                              answered Jun 24 at 2:52









                              nutboltu

                              1,45121428




                              1,45121428






















                                  up vote
                                  0
                                  down vote













                                  Are you sure your HTML file can see your script. Why not try running small tests on the console window. View of the output of those elements and see if it gives null.






                                  share|improve this answer

























                                    up vote
                                    0
                                    down vote













                                    Are you sure your HTML file can see your script. Why not try running small tests on the console window. View of the output of those elements and see if it gives null.






                                    share|improve this answer























                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      Are you sure your HTML file can see your script. Why not try running small tests on the console window. View of the output of those elements and see if it gives null.






                                      share|improve this answer












                                      Are you sure your HTML file can see your script. Why not try running small tests on the console window. View of the output of those elements and see if it gives null.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jun 24 at 4:13









                                      mobfire

                                      1




                                      1






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51006577%2fcreate-button-element-in-javascript%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Create new schema in PostgreSQL using DBeaver

                                          Deepest pit of an array with Javascript: test on Codility

                                          Costa Masnaga