Sceptical Jule Sceptical Jule - 6 months ago 29
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


Try ...

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

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