javascript - Generate <li> from array in <div> -


im geting error uncaught typeerror: cannot read property 'appendchild' of null , dont know why:

im trying make list array , display on div

var options = [      set0 = ['option 1', 'option 2'],      set1 = ['first option', 'second option', 'third option']  ];    function makeul(array) {      // create list element:      var list = document.createelement('ul');        (var = 0; < array.length; i++) {          // create list item:          var item = document.createelement('li');            // set contents:          item.appendchild(document.createtextnode(array[i]));            // add list:          list.appendchild(item);      }        // finally, return constructed list:      return list;  }    // add contents of options[0] #foo:  document.getelementbyid("foo").appendchild(makeul(options[1]));
<div  id="foo"></div>

the following solve problem

<html> <head> <script type="text/javascript"> var options = [         set0 = ['option 1','option 2'],         set1 = ['first option','second option','third option']                                     ];          function makeul(array) {          // create list element:         var list = document.createelement('ul');          for(var = 0; < array.length; i++) {          // create list item:           var item = document.createelement('li');           // set contents:              item.appendchild(document.createtextnode(array[i]));              // add list:             list.appendchild(item);                         }              // finally, return constructed list:                         return list;                     }              // add contents of options[0] #foo:             function do()             {                 document.getelementbyid("foo").appendchild(makeul(options[1]));             } </script> </head> <body onload="do()"> <div id="foo"></div> </body> </html> 

the reason error occurs because javascript executed before body of html loads cannot find div object. if check via developer tools document.body going null right before function executes. however, if execute function when body loads find foo elem.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -