1
HTML:
<select id="list">
    <option value="A">Alpha</option>
    <option value="B">Bravo</option>
    <option value="D">Delta</option>
</select>

jQuery:
$("#list").append("<option value=\"C\">Charlie</option>");

Is there any easy way to get option C between B and D?

Espen
  • 3,479
  • 11
  • 45
  • 71

4 Answers4

0

You could use insertAfter():

$("<option value=\"C\">Charlie</option>").insertAfter('#list > option[value="B"]');

...or insertBefore():

$("<option value=\"C\">Charlie</option>").insertBefore('#list > option[value="D"]');

Here's a fiddle

billyonecan
  • 19,687
  • 8
  • 41
  • 62
0
$("option[value='B']").after("<option value=\"C\">Charlie</option>");

More information in after() and insertAfter() (both doing the same bt taking different ways) in the official docu.

Zsolt Szilagyi
  • 4,274
  • 4
  • 25
  • 43
0

Try this using before():

$("#list option[value=D]").before("<option value='C'>Charlie</option>");

This will insert the new option Charlie, specified by the parameter, before the option Delta.

palaѕн
  • 68,816
  • 17
  • 108
  • 129
0

You can try with attribute selectors:

$("<option value=\"C\">Charlie</option>").insertAfter($('#list option[value*="B"]'));

Fiddle

Jai
  • 72,925
  • 12
  • 73
  • 99