Reputation: 760
I have html select,
<select id="myselect">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
I need to add new option in this select. If I try like this:
$('#myselect').appendTo($('<option>my-option</option>'));
the my-option have added to the end
<select id="myselect">
<option>1</option>
<option>2</option>
<option>3</option>
<option>my-option</option>
</select>
How can I add an option in the beginning (as first)? Like this:
<select id="myselect">
<option>my-option</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Upvotes: 14
Views: 14064
Reputation: 147553
In plain old javascript (POJS) you'd use insertBefore()
, e.g.
var select = document.getElementById('mySelect');
var opt = new Option('', 'my-option');
select.insertBefore(opt, select.firstChild);
Upvotes: 18
Reputation: 50029
Use prependTo()
You might have meant this $('#myselect').prependTo($('my-option'));//typo?
$('#myselect').prepend($('<option>my-option</option>'));
http://api.jquery.com/prependTo
http://api.jquery.com/prepend/
But your code is actually the other way around. This might be a typo. In any case, the methods available are prepend()
and prependTo()
Upvotes: 4
Reputation: 238115
First, you mean append
, rather than appendTo
. append
adds the content of the parameter to the selection; appendTo
appends the selection to the element designated in the parameter.
Second, perhaps intuitively, you can use prepend
:
$('#myselect').prepend($('<option>my-option</option>'));
Upvotes: 16