I am using the innerHTML function to dynamically create a drop-down menu in HTML and populate it with certain parameters. Here is my code:
for (i in categories) {
var cat_name = i;
var cats = categories[cat_name];
P2_txt.innerHTML += cat_name;
if (cats.length > 2) {
// Drop Down Menu Needed
P2_txt.innerHTML += '<select>';
for (var j = 0; j < cats.length; j++) {
P2_txt.innerHTML += '<option>'+cats[j]+'</option>';
}
P2_txt.innerHTML += '</select>';
}
}
However when I run it, the following HTML code is generated:
<select></select>
<option>Value of cats[0]</option>
<option>Value of cats[1]</option>
<option>Value of cats[2]</option>
Instead of what I want, which is this:
<select>
<option>Value of cats[0]</option>
<option>Value of cats[1]</option>
<option>Value of cats[2]</option>
</select>
Any thoughts?
When you modify
innerHTMLit’s immediately parsed into the DOM… so you’ve effectively added aselectelement followed by a bunch ofoptionelements out of the intended hierarchy.So, you either:
innerHTMLcreateElementandappendChildand so forth instead of ugly string concatenation.