Sometimes, we want to add drop-down list programmatically with JavaScript.
In this article, we’ll look at how to add drop-down list programmatically with JavaScript.
How to add Drop-Down list programmatically with JavaScript?
To add drop-down list programmatically with JavaScript, we can use some DOM manipulation methods.
For instance, we write
const myParent = document.body;
const array = ["Volvo", "Saab", "Mercades", "Audi"];
const selectList = document.createElement("select");
selectList.id = "mySelect";
myParent.appendChild(selectList);
for (const a of array) {
const option = document.createElement("option");
option.value = a;
option.text = a;
selectList.appendChild(option);
}
to get the body element with document.body.
Then we create a select element with createElement.
Next, we set its id with
selectList.id = "mySelect";
Then we append the select element as the last child of the body with
myParent.appendChild(selectList);
Next, we loop through the array with a for-of loop.
In it, we create an option element with createElement.
Then we set its value attribute and the text of the option element.
And then we call selectList.appendChild with option to append the option as the last child of the select.
Conclusion
To add drop-down list programmatically with JavaScript, we can use some DOM manipulation methods.