4
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 the console.log brings the cute results as it should be. But when printing the object it brings the following error.
Uncaught Typeerror: Cannot read Property 'appendchild' of null.
So I ran here in the stack and it worked but in my code remains the same error, that thing.
– Alison Paulo
Then there should be no element with id
estado
.– Jéf Bueno
Found the problem @Alisonpaulo?
– Jéf Bueno
So I think so, but I’m not finding a way to solve it. For example html and js are separated, ids are equal, what I think html is not doing the request, I do not know if I have to do some event to send id to js
– Alison Paulo
That doesn’t make much sense. Or I got it all wrong.
– Jéf Bueno
Javascript is not running tapirs of the creation of the elements, right? This may be the problem.
– Jéf Bueno
look at the codes are exactly like your answer, if I debug with cosole.log without printar select.appendchild(el); it shows the 5 states, but when printo select.appendchild(el); it gives the error. That’s what I don’t understand.
– Alison Paulo
Javascript is not running before HTML creation?
– Jéf Bueno
That’s right, that drug I lost 2 hours atoa. I was making the call in the head, I changed the location of the call worked out. Vlw ai brother thanks even.
– Alison Paulo
there is some difference in using . appendchild or . add?
– SuperMax