To add a select element programmatically with JavaScript, we can use the document.createElement
method to create elements.
Then we can use the appendChild
method to append child elements into the parent element.
For instance, we can write the following HTML:
<div>
</div>
to add the parent element for the select element.
Then we can add the select element with the option elements in it by writing:
const myParent = document.querySelector('div');
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);
}
We get the div with:
const myParent = document.querySelector('div');
Then we create the select element with:
const selectList = document.createElement("select");
Then we set the id
attribute of the select element with:
selectList.id = "mySelect";
Then we append the select element as a child of the div with:
myParent.appendChild(selectList);
Next, we add the option elements into the select element by writing:
for (const a of array) {
const option = document.createElement("option");
option.value = a;
option.text = a;
selectList.appendChild(option);
}
We loop through the array
with the for-of loop.
In the loop body, we call document.createElement
with 'option'
to create the option element.
We set option.value
to set the value
attribute of the option element.
And we set the text
property to set the option text to display.
Next, we call selectList.appendChild
with option
to append option
to the select element as its child.