How to add Drop-Down list (<select>) programmatically?

Christos Baziotis picture Christos Baziotis · Jun 8, 2013 · Viewed 160.6k times · Source

I want to create a function in order to programmatically add some elements on a page.

Lets say I want to add a drop-down list with four options:

<select name="drop1" id="Select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

How can I do that?

Answer

tymeJV picture tymeJV · Jun 8, 2013

This will work (pure JS, appending to a div of id myDiv):

Demo: http://jsfiddle.net/4pwvg/

var myParent = document.body;

//Create array of options to be added
var array = ["Volvo","Saab","Mercades","Audi"];

//Create and append select list
var selectList = document.createElement("select");
selectList.id = "mySelect";
myParent.appendChild(selectList);

//Create and append the options
for (var i = 0; i < array.length; i++) {
    var option = document.createElement("option");
    option.value = array[i];
    option.text = array[i];
    selectList.appendChild(option);
}