I had to dynamically populate an HTML select element via the DOM and Javascript.
I did a little research and I got things working with no problem, but I had some further questions.
I found 2 stackoveflow posts and another non-stack blog post concerning how to populate Select Elements:
- JavaScript - populate drop down list with array
- innerHTML replace does not reflect
- https://allofetechnical.wordpress.com/2010/05/28/using-innerhtml-to-update-a-select-differences-between-ie-and-ff/
All 3 articles are anywhere from 8 - 10 years old. They seem to favor a certain technique discussed below due to older browsers NOT being able to use 'innerHTML' DOM property.
All 3 of these articles instruct to populate Select Elements via the DOM using: document.createElement("option").
A number of people have tried to use the 'Element.innerHTML' DOM property to populate Select Elements with a STRING of options rather than using document.createElement("option").
Apparently, these people are then instructed to use document.createElement("option") rather than 'innerHTML' beacause 'innerHTML' has some known issues in older browsers such as Internet Explorer.
Normally, I would not look into this any further and just go with document.createElement("option") but I have 2 concerns:
I am populating 2 Select Elements with 190 Options each (380 total) and each option represents an ISO Language Code.
So through each iteration of Array.prototype.forEach() the Javscript application is creating an object for each and every ISO language code. That's 380 objects total in memory.
Isn't document.createElement("option") inefficient when compared to just building a very large String of options and inserting via 'innerHTML?'
I have tested the 'innerHTML' way in the latest Chrome and Firefox browsers and it works fine.
I have no intention of supporting older browsers such as Internet Explorer so is 'innerHTML' a viable option in my case?
I would really like to use 'innerHTML' as the code is so much more readable (and saves memory?):
Array.prototype.map().toString
gives me the full String of options.
Any thoughts on this matter would be greatly appreciated.