I have the following select element in my html file:
<select id="usr-slct">
</select>
to which I am trying to add some options using javascript in a script tag just before the end of the document's body. Like this:
var selector = document.getElementById("usr-slct");
var newoption = document.createElement("option").text="User1";
selector.add(newoption);
I would like to know why this code does not make my page display the new option in the select and how can I make it work as intended?
document.createElement("option").text="User1" returns "User1", the result of the assignment, not a HTMLOptionElement. You should code:
var newoption = document.createElement("option");
newoption.text = "User1";
selector.add(newoption);
edit: OP is using .add() method for adding an option to the select element. HTMLSelectElement object does have .add() method.
Your select element has an 'options' property, which is an array. You can create new options by using:
selector.options[selector.options.length] = new Option('text1', 'value1');
This would add a new Option, with text of text1 and value of value1, to the end of the selector's options array which would return the result you are looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With