Sceptical Jule Sceptical Jule - 3 months ago 5
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

Try ...

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

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

Comments