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,607
  • 11
  • 48
  • 75

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
  • 20,090
  • 8
  • 42
  • 64
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,741
  • 4
  • 28
  • 44
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ѕн
  • 72,112
  • 17
  • 116
  • 136
0

You can try with attribute selectors:

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

Fiddle

Jai
  • 74,255
  • 12
  • 74
  • 103