I would like to add options to a Select dropdown menu via Javascript.
The Select dropdown is called myWidth. The options are in the array myOptions.
I now use the following code which I found on the internet. However, I am sure it can be more compact and readable:
var select = document.getElementById("myWidth");
for(var i = 0; i < myOptions.length; i++) {
var opt = myOptions[i];
var el = document.createElement(“option”);
el.textContent = opt;
el.value = opt;
select.appendChild(el);
No that is pretty much what you need to do. I would advise that you use let where possible though as var makes global variables which is not a good idea in most circumstances.
Did you have a specific problem with this or were you looking to just make it shorter?
There is little point making it shorter but you can delete the penultimate line because if no value attribute is included, the value defaults to the text content.