-2

I am trying to create a button and append it to HTML in Javascript.

This is my code:

<html>

    <head>
        <script>
             var btn=document.createElement("button");
             btn.className = "YourClass";
             btn.className += " YourClass2";
             btn.id ='someId';
             document.getElementById("main").appendChild(btn);
        </script>
    </head>

    <body>
        <div id = 'main'>
        </div>
    </body>

</html>

Unfortunately, this does not work and i don't understand why.

user1584421
  • 3,499
  • 11
  • 46
  • 86
  • Try to put you script tag just before body ends... – vaku Aug 14 '19 at 17:30
  • It fails because you run your JavaScript code before the page has been rendered. Try moving it to before the closing body tag – j08691 Aug 14 '19 at 17:31
  • Most likely because in the time of script evaluation, there is no `div` with id `main` yet. Try to put the script right before enclosing `body` tag. – HynekS Aug 14 '19 at 17:31

1 Answers1

-1

Just need to move your script tags beneath the DIV you're targetting...the JS loads and references the DIV before it is even loaded. Also .classList is a much nicer way to manage classes on elements :)

<html>
<head>
</head>
<body>
  <div id="main"></div>

  <script>
    var btn=document.createElement("button");
    btn.classList.add('YourClass', 'YourClass2');

    btn.appendChild(document.createTextNode('Press me'));

    btn.id ='someId';
    document.getElementById("main").appendChild(btn);
  </script>
</body>

</html>
James Allen
  • 969
  • 4
  • 16