Reputation: 1781
I am struggling to understand to why my code only creates this single option:
And not options from 0 to 10?
<div>
<div id="SelectEl">
</div>
</div>
<script>
// Get el ID
var el = document.getElementById('SelectEl');
// Select element
var selectList = document.createElement('select');
// Option element
var option = document.createElement('option');
for (var i = 0; i < 11; i++) {
// Add selectList element to div
el.appendChild(selectList);
// Add option to selectList
selectList.appendChild(option);
// Add text of a number 0 to 10
option.text = [i]
}
</script>
Upvotes: 0
Views: 136
Reputation: 12218
Create the option element inside the loop, one for each iteration, and move the line where you append the selectList to the div to outside the loop:
const el = document.getElementById('SelectEl');
const selectList = document.createElement('select');
el.appendChild(selectList);
for (var i = 0; i < 11; i++) {
var option = document.createElement('option');
selectList.appendChild(option);
option.text = [i]
}
<div id="SelectEl"></div>
Upvotes: 1
Reputation: 24965
<div>
<div id="SelectEl">
</div>
</div>
<script>
// Get el ID
var el = document.getElementById('SelectEl');
// Select element
var selectList = document.createElement('select');
// Option element
var option;
for(var i = 0; i < 11; i++) {
option = document.createElement('option');
// Add text of a number 0 to 10
option.text = [i]
// Add option to selectList
selectList.appendChild(option);
}
// Add selectList element to div
el.appendChild(selectList);
</script>
Upvotes: 2