Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKristian Woods
23,414 PointsHow do you add an option to a select element via javascript?
I'm trying to add the items inside an array to a dropdown menu. However, I can't get it to work.
here is my code,
thanks in advance
<select name="" id="drop1">
</select>
let dropDownMenu = document.querySelector('#drop1');
let array = ['coffee', 'milk', 'sugar'];
for(let i = 0; i < array.length; i++) {
let option;
option.innerHTML = '<option>' + array[i] + '</option>';
dropDownMenu.appendChild(option);
}
1 Answer
Steven Parker
231,248 PointsYou're mixing two different element creation methods. To append an element, it must first be created:
for(let i = 0; i < array.length; i++) {
let option = document.createElement('option');
option.textContent = array[i];
dropDownMenu.appendChild(option);
}
The less elegant but more concise way would be to simply add the new HTML to the select
:
for(let i = 0; i < array.length; i++) {
dropDownMenu.innerHTML += '<option>' + array[i] + '</option>';
}
Kristian Woods
23,414 PointsKristian Woods
23,414 PointsHey Steven, thanks for your reply! I was hoping that you could help me further? I'm trying to create a dymanic dropdown menu. Depending on what the user clicks, it will populate a second drop-down menu.
The problem I'm having, is that the drop-down menu continues to add new items on top of the previous items. I want the list to change, and remove items, based on what the user clicks.
Steven Parker
231,248 PointsSteven Parker
231,248 PointsA quick way to clear the contents of an element is to set the
innerHTML
to an empty string. So you could add this line as the first thing in the dynamicList function:menu.innerHTML = "";
You could also loop through the elements and use remove or removeChild, but this is faster.