Categories
JavaScript Answers

How to populate drop down list with array with JavaScript?

Spread the love

Sometimes, we want to populate drop down list with array with JavaScript.

In this article, we’ll look at how to populate drop down list with array with JavaScript.

How to populate drop down list with array with JavaScript?

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.

Conclusion

To populate drop down list with array with JavaScript, we call the createElement method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *