I want to generate options from 12 to 100 inside a element with id=“mainSelect” without manually writing all the tags.
What’s the best way to JavaScript add option to select dynamically?
Here’s what I have so far:
function selectOptionCreate() {
var age = 88;
line = "";
for (var i = 0; i < 90; i++) {
line += "<option>";
line += age + i;
line += "</option>";
}
return line;
}
Instead of building an HTML string, use DOM methods to create and add elements directly:
js
Copy
Edit
function addOptions() {
const select = document.getElementById('mainSelect');
for (let i = 12; i <= 100; i++) {
const option = document.createElement('option');
option.value = i;
option.textContent = i;
select.appendChild(option);
}
}
addOptions();
This approach avoids innerHTML manipulation and is more robust and secure.
If you prefer building a string and inserting it at once, update your function to generate the full options string, then assign it:
js
Copy
Edit
function selectOptionCreate() {
let options = "";
for (let i = 12; i <= 100; i++) {
options += `<option value="${i}">${i}</option>`;
}
document.getElementById('mainSelect').innerHTML = options;
}
selectOptionCreate();
This is simple and works well if you want to replace all existing options.
For better performance when adding many options, use a DocumentFragment:
function addOptionsEfficiently() {
const select = document.getElementById('mainSelect');
const fragment = document.createDocumentFragment();
for (let i = 12; i <= 100; i++) {
const option = document.createElement('option');
option.value = i;
option.textContent = i;
fragment.appendChild(option);
}
select.appendChild(fragment);
}
addOptionsEfficiently();
This minimizes DOM reflows by batching DOM changes, especially useful if your select options list gets larger.