Reputation: 201
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?
Upvotes: 3
Views: 6260
Reputation: 144659
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.
Upvotes: 1
Reputation: 69276
The issue here is that you're doing this:
var newoption = document.createElement("option").text = "User1";
which is two times wrong:
First of all, in Javascript, an assignment returns the assigned value, so assigning "User1"
to the text property of the newly created option results in your variable holding the string "User1"
, not the element; you have to first create the element and then change its text.
Secondly, you should change the textContent
property, not the text
property, which doesn't mean anything to the DOM.
Here's the correct code:
var selector = document.getElementById("usr-slct");
var newoption = document.createElement("option");
newoption.textContent = "User1";
selector.add(newoption);
Upvotes: 0
Reputation: 5286
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.
Upvotes: 1