How to add Drop-Down list (<select>) programmatically?

前端 未结 9 2226
北恋
北恋 2020-11-27 14:12

I want to create a function in order to programmatically add some elements on a page.

Lets say I want to add a drop-down list with four options:

<         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 14:36

    This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.

    var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi'];
    
    var sEle = document.createElement('select');
    document.getElementsByTagName('body')[0].appendChild(sEle);
    
    for (var i = 0; i < array.length; ++i) {
      var oEle = document.createElement('option');
    
      if (i == 0) {
        oEle.setAttribute('disabled', 'disabled');
        oEle.setAttribute('selected', 'selected');
      } // end of if loop
    
      var oTxt = document.createTextNode(array[i]);
      oEle.appendChild(oTxt);
    
      document.getElementsByTagName('select')[0].appendChild(oEle);
    } // end of for loop

提交回复
热议问题