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

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

    const cars = ['Volvo', 'Saab', 'Mervedes', 'Audi'];
    
    let domSelect = document.createElement('select');
    domSelect.multiple = true;
    document.getElementsByTagName('body')[0].appendChild(domSelect);
    
    
    for (const i in cars) {
      let optionSelect = document.createElement('option');
    
      let optText = document.createTextNode(cars[i]);
      optionSelect.appendChild(optText);
    
      document.getElementsByTagName('select')[0].appendChild(optionSelect);
    }

提交回复
热议问题