How to populate the options of a select element in javascript

You can create the option inside the loop;

for(element in langArray)
{
   var opt = document.createElement("option");
   opt.value= index;
   opt.innerHTML = element; // whatever property it has

   // then append it to the select element
   newSelect.appendChild(opt);
   index++;
}

// then append the select to an element in the dom

2023 Update:

To make sure we avoid creating globals and remain in the correct scope, we can use map() and let.

let selectTag = document.createElement('select');
langArray.map( (lang, i) => {
    let opt = document.createElement("option");
    opt.value = i; // the index
    opt.innerHTML = lang;
    selectTag.append(opt);
});

Leave a Comment