how to dynamically add options to an existing select in vanilla javascript

后端 未结 6 514
面向向阳花
面向向阳花 2020-11-29 20:16

I\'d like to add option to a select dynamically using plain javascript. Everything I could find involves JQuery or tries to create the select dynamically as well. The clos

6条回答
  •  清酒与你
    2020-11-29 20:40

    The simplest way is:

    selectElement.add(new Option('Text', 'value'));
    

    Yes, that simple. And it works even in IE8. And has other optional parameters.

    See docs:

    • HTMLSelect​Element​.add(item[, before])
    • new Option(text, value, defaultSelected, selected);

提交回复
热议问题