Blog>
Snippets

Dynamic Select Box Creation

Create and append a new `<select>` element populated with `<option>` elements based on a JavaScript array of values.
// Create a select element
var select = document.createElement('select');
This line creates a new HTML select element.
// Array of options to add
var options = ['Option 1', 'Option 2', 'Option 3'];
This line defines an array of option values that will be added to the select box.
// Populate select element with options
options.forEach(function(text) {
    var option = document.createElement('option');
    option.textContent = text;
    option.value = text;
    select.appendChild(option);
});
These lines iterate over the options array and create an option element for each item, which is then appended to the select element.
// Append the select element to the DOM
var container = document.querySelector('#select-container');
container.appendChild(select);
These lines select an existing container element in the DOM and append the newly created select element to that container.