JavaScript: add extra attribute after new Option()

▼魔方 西西 提交于 2019-12-02 20:32:42

you can do something like


var o1 = new Option("key","value");
selbox.options[selbox.options.length] = o1;
o1.setAttribute("key","value");

I know this is old but I came across this question when I forgot it's add and not push today.

The correct way is to use select.options.add.

 var opt = document.createElement('option');
 opt.value = 'hello';
 opt.text = 'world';
 opt.setAttribute('data-discount', 'integer');
 selbox.options.add(opt);

You can combine this into one line of code:

(selbox.options[selbox.options.length] = new Option("key","value")).setAttribute("key","value");

Note that this will only work if you have just one attribute to add, otherwise you will need a temporary variable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!