Downloading Array Javascript in a Combobox

Question:

I would like help with this little problem, I have to make a combobox that 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 results cute as it should be. But when printing the object it brings the following error.

Uncaught TypeError: Cannot read property 'appendChild' of null.

Answer:

The id should be in the select and not in the option .

Anyway, the current code shouldn't present the error you showed, this seems more like a problem with the order of things, that is, make sure you're not calling the script before creating the elements, this is a very common error.

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>
Scroll to Top