1

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?

1
  • 5
    Create the HTML string first, then assign it to .innerHTML. Commented Nov 27, 2012 at 20:15

2 Answers 2

7

When you modify innerHTML it's immediately parsed into the DOM... so you've effectively added a select element followed by a bunch of option elements out of the intended hierarchy.

So, you either:

  1. Build your entire combobox markup and then add it to innerHTML
  2. or use the DOM methods createElement and appendChild and so forth instead of ugly string concatenation.

var categories = { "Domestic": ["Tabby", "Siamese"], "Wild": ["Cougar", "Tiger", "Cheetah"] }, cats, combo, frag = document.createDocumentFragment(); for (var category in categories) { cats = categories[category]; frag.appendChild(document.createTextNode(category)); combo = document.createElement("select"); for (var i = 0, ln = cats.length; i < ln; i++) { combo.appendChild(document.createElement("option")).textContent = cats[i]; } frag.appendChild(combo); } document.body.appendChild(frag);

Sign up to request clarification or add additional context in comments.

Comments

3

NEVER use += with innerHTML unless you are appending fully complete HTML.

As such, you should be creating a string, var str = ""; ... str += "...";, then appending that: P2_txt.innerHTML += str;.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.