1

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?

2
  • 2
    Wrap you code in DOMContentLoaded and reference the JS file at the after DOM element Commented May 24, 2017 at 13:49
  • You tagged this with jquery, but don't seem to use it? Commented May 24, 2017 at 13:52

4 Answers 4

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
});
Sign up to request clarification or add additional context in comments.

Comments

0

JQuery way

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

Comments

0

try to use

$( document ).ready(function() {
   //set your code 
});

Comments

-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 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.