Sceptical Jule Sceptical Jule - 1 year ago 81
Javascript Question

Change position of an option using JavaScript

I have a dropdown list with several options and now I want to insert a new option to the top of the list. How do I do that?

function insertOptionAll (DOMtarget)
var option = document.createElement("option");
option.text = "Some option";
option.value = 0;
option.title = "Some option";
DOMtarget.add(option); //appends to the end
//DOMtarget.options[DOMtarget.options.length - 1].index = 0; --> doesnt work

Answer Source

Try ...

DOMtarget.insertBefore(option, DOMtarget.options[0]);

See: Add new <option> to all dropdown <select> tags using javascript

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download