Sometimes, we want to add options to an HTML select element with JavaScript.
In this article, we’ll look at how to add options to an HTML select element with JavaScript.
Using the document.createElement Method
We can use the document.createElement
method to create a new option element.
Then we can call appendChild
on the select element to append it as a child of the select element.
For instance, we can write the following HTML:
<select>
</select>
to create an empty select element.
Then we can add the option elements for the select element by writing:
const select = document.querySelector('select')
const arr = ['apple', 'orange', 'grape']
for (const [index, a] of arr.entries()) {
const opt = document.createElement('option');
opt.value = index;
opt.innerHTML = a;
select.appendChild(opt);
}
We get the select element with document.querySelector
.
Then we define the arr
array with the option text we want to add.
Next, we have a for-of loop to loop through the arr
entries.
We call arr.entries
to return an array with the index and the value of the array entry each in their own array.
In the loop body, we call document.createElement
to create the option element.
Next, we set the value
property to set the value of the value
attribute of the option element.
Then we set the innerHTML
property to set the content that the user sees in the drop-down for each option.
And finally, we call select.appendChild
with the opt
element object to add it as a child of the select element.
Therefore, now we should see a drop-down with apple, orange, and grape as options.
Conclusion
We can add options into the select HTML element with the document.createElement
method.
Then we can append the created option element to the select element with appendChild
.