0

I been trying to have an array populate a drop down, I got this examples from this post: JavaScript - populate drop down list with array

I'm using this html:

 <select id="selectNumber">
 <option>Choose a number</option>
 </select>

with this js

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}​

But it only works if I place the js inside the HTML document, if I place it on a separate file it gives me this errror in Chrome:

>Uncaught TypeError: Cannot read property 'appendChild' of null  at g.js:8

I also tryed this one but same thing happens:

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.text = opt;
el.value = opt;
select.add(el);
}​

The code only works if I put it inside the HTML file but if i have it on a separate file it gives me that error.

Any idea why?

Satpal
  • 132,252
  • 13
  • 159
  • 168
pumsho
  • 21
  • 7
  • 2
    Wrap you code in [DOMContentLoaded](https://developer.mozilla.org/en/docs/Web/Events/DOMContentLoaded) and reference the JS file at the after DOM element – Satpal May 24 '17 at 13:49
  • You tagged this with `jquery`, but don't seem to use it? – trincot May 24 '17 at 13:52

4 Answers4

2

You should load the js file at the end of the body. This will ensure you that the element your are looking for exists in your DOM.

This can be avoided by using a ready check. Native Javascript example:

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});
Peter Bode
  • 222
  • 1
  • 9
0

JQuery way

$(() => { //dom ready, my code here can access the dom })

roberto tomás
  • 4,435
  • 5
  • 42
  • 71
0

try to use

$( document ).ready(function() {
   //set your code 
});
Jay
  • 703
  • 9
  • 21
-2

<script src="filename.js"></script>

try adding this in head tag if problem persists make sure that you have placed JS file in the same folder as of html file

  • 1
    as you can see the JS is loading so OP must have loaded the JS. the problem is likely related to the fact that the DOM is not ready when the script is loaded as mentioned in other answers already – Ovidiu Dolha May 24 '17 at 13:59