To populate drop down list with array with JavaScript, we call the createElement
method.
For instance, we write
const arr = ["1", "2", "3", "4"];
arr.forEach((item) => {
const optionObj = document.createElement("option");
optionObj.textContent = item;
document.getElementById("myselect").appendChild(optionObj);
});
to call arr.forEach
with a callback that calls createElement
to create an option element.
Then we set the text of the option by setting the textContent
property.
Then we select the select element and append the option element to it with appendChild
.