Asked  7 Months ago    Answers:  5   Viewed   35 times

What's the easiest way to add an option to a dropdown using jQuery?

Will this work?

$("#mySelect").append('<option value=1>My option</option>');



This did NOT work in IE8 (yet did in FF):

$("#selectList").append(new Option("option text", "value"));

This DID work:

var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
Tuesday, June 1, 2021
answered 7 Months ago


$("#id option").each(function()
    // Add $(this).val() to your list

.each() | jQuery API Documentation

Tuesday, June 1, 2021
answered 7 Months ago

Try this:

$(".ct option[value='X']").each(function() {

Or to be more terse, this will work just as well:

$(".ct option[value='X']").remove();
Thursday, June 3, 2021
answered 7 Months ago

Doing a little digging, I can see this issue raised on GitHub.

One option is to check to see if the value exists, and append it if it doesn't.

var s2 = $("#selectEvents").select2({
    placeholder: "Choose event type",
    tags: true

var vals = ["Trade Fair", "CA", "Party"];

if(!s2.find('option:contains(' + e + ')').length) 

<script src=""></script>
<script src=""></script>
<link href="" rel="stylesheet"/>

<select multiple name="event_type[]" class="form-control" id="selectEvents">
  <option>Trade Fair</option>
Tuesday, August 3, 2021
answered 5 Months ago

adding context to the selector is much faster than refining your selector

This is true in the general case. With respect to your specific examples however it is not necessarily true for jQuery <= 1.2.6.

Up to and including jQuery 1.2.6 the selector engine worked in a "top down" (or "left to right") manner. Meaning that both your examples would operate like this (roughly):

var root = document.getElementById('bar');
return root.getElementsByTagName('li');

jQuery 1.3.x (ie, Sizzle, which jQuery embeds) introduced a "bottom up" (or "right to left") approach to querying the DOM. So $('#bar li') now becomes (roughly):

var results = [];
var elements = document.getElementsByTagName('li');
for(var i=0; i < elements.length; i++) {
    var element = elements[i];
    var parent = element.parentNode;
    while(parent) {
        if( == 'bar') {
        parent = parent.parentNode;
return results

There are benefits and downsides to both approaches. You found one of the downsides.

Edit: just found out from this discussion that Sizzle trunk now makes a special exemption of selectors where #id is first. It uses that as the root context, speeding things up a bit. This should diminish if not eliminate the speed differences you are seeing.

Tuesday, August 10, 2021
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :