Download Javascript Array in a Combobox

3

I would like help in this small problem, I have to do a combobox shows 5 states being loaded by an array in javascript, my code is like this.

HTML

<select >
    <option id="estado"></option>
</select>

My Javascript is like this

var select = document.getElementById("estado"); 
var options = ["São Paulo", "Rio de Janeiro", "Paraná", "Pernambuco", "Rio Grande do Sul"]; 

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

Debugging in console.log it brings the cute results as it should be. But at the time of printing the object it brings the following error.

  

Uncaught TypeError: Can not read property 'appendChild' of null.

    
asked by anonymous 15.05.2017 / 16:37

1 answer

3

The id should be in select and not option .

Anyway the current code should not show the error you showed, this seems more of a problem with the order of things, ie make sure you are not calling script before creating elements, this is a common mistake.

var select = document.getElementById("estado"); 
var options = ["São Paulo", "Rio de Janeiro", "Paraná", "Pernambuco", "Rio Grande do Sul"]; 

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);
}
<select id="estado">
    <option></option>
</select>
    
15.05.2017 / 16:39