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

前端 未结 9 2239
北恋
北恋 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:12

    This will work (pure JS, appending to a div of id myDiv):

    Demo: http://jsfiddle.net/4pwvg/

    var myParent = document.body;
    
    //Create array of options to be added
    var array = ["Volvo","Saab","Mercades","Audi"];
    
    //Create and append select list
    var selectList = document.createElement("select");
    selectList.id = "mySelect";
    myParent.appendChild(selectList);
    
    //Create and append the options
    for (var i = 0; i < array.length; i++) {
        var option = document.createElement("option");
        option.value = array[i];
        option.text = array[i];
        selectList.appendChild(option);
    }

提交回复
热议问题