Search code examples
javascripthtmldomappendchild

Appending new DOM elements to existing elements


I am trying dynamically increase the number of selects my form has on a website. I use javascript to do so.

JS code:

  var div = document.getElementById("graph-form");
  var para = document.createElement('span');
  para.innerHTML = "Test Type";
  var form = document.getElementById("form-id");
  var selectList = document.createElement("select");
  selectList.setAttribute("name","Test");
  for(var i = 0; i < test_form_values.length; i++){
    var option = document.createElement("option");
    option.value = test_form_values[i];
    option.text = test_form_text[i];
    selectList.appendChild(option);
  }
  form.appendChild(para);
  form.appendChild(selectList);
  var para = document.createElement('span');
  para.innerHTML = "Parameter";
  var selectList = document.createElement("select");
  selectList.setAttribute("name","Parameter");
  for(var i = 0; i < param_form_values.length; i++){
    var option = document.createElement("option");
    option.value = param_form_values[i];
    option.text = param_form_text[i];
    selectList.appendChild(option);
  }
  form.appendChild(para);
  form.appendChild(selectList);

Html code:

  <form action="/analytics" method = "post"></form>
  <div id = "form-id">
  <span>Test Type </span>
  <select name="Test">
    <option value="Aop2DContact">AOP 2D Contact</option>
    <option value="Aop2DMag">AOP 2D Magnification</option>
  </select>
  <span>Parameter </span>
  <select name="Parameter">
    <option value="MTF1">MTF at 2 lp/mm parallel</option>
    <option value="MTF2">MTF at 4 lp/mm parallel</option>
  </select>
    </div>
  <div class="buttons">
    <input type="submit">
  </div>
</form>

After appending:

enter image description here

After I append the newly created elements, it not only doesn't append inside the element but takes the div I had placed inside the element and moved it outside. I feel like there is probably an obvious answer as to why my HTML is getting restructured but I am not sure what that is.


Solution

  • Like Turnip commented, you are ending your form right after you open it.

    Also, your JS is looking to append to the element with the id "form-id" and your form does not have that id, your inner div does.