javascripthtmldom

Create an array of buttons from Javascript array


I want to create a bunch of buttons in the html body based on an array stored in Javascript. Here is my code:

<!DOCTYPE>
<html>
     <head>
           <script>
                var listBrand =['LEXUS','AUDI','MAYBACK','FERRARI','TOYOTA'];   
                //the array
                function printBtn() {
                    for (var i = 0; i < listBrand.length; i++) {
                       var btn = document.createElement("button");
                       var t = document.createTextNode(listBrand[i]);
                       btn.appendChild(t);
                       document.body.appendChild(btn);
                    }
                }
           </script>  
     </head>
     <body>
          <div onload="printBtn();">
          
          </div>
     </body>
</html>

I want to have all 5 buttons LEXUS, AUDI, MAYBACK, FERRARI, and TOYOTA show up in the body when the page loads, but the buttons fail to appear.

Is there anything wrong with my code? Any help and/or explanations are appreciated. Thank you.


Solution

  • The onload event can only be used on the document/body, frames, images, and scripts.

    It can be attached to only body and/or each external resource. The div is not an external resource, so the onload event doesn't apply there.

    Use following:

    <body onload="printBtn();">
    

    Instead of

    <div onload="printBtn();">
    

    And you are good to go.

    Maybe you should take a look at window.onload vs document.onload here on SO too.