admin管理员组文章数量:1434893
I'm dynamically creating option elements for a drop down menu using Javascript and would like to know how to add a class to them so that I can style them with CSS.
I have the following code:
for (var i=0;i<portfolio.length-1;i++) {
portfolioSelect.options[portfolioSelect.options.length] =
new Option(portfolio[i]);
}
where portfolio is an array populated by an outside source.
HTML where options inserted:
<select id="portfolio" name="portfolio">
<option selected="selected" value="Select One">Select One</option>
</select>
I'm dynamically creating option elements for a drop down menu using Javascript and would like to know how to add a class to them so that I can style them with CSS.
I have the following code:
for (var i=0;i<portfolio.length-1;i++) {
portfolioSelect.options[portfolioSelect.options.length] =
new Option(portfolio[i]);
}
where portfolio is an array populated by an outside source.
HTML where options inserted:
<select id="portfolio" name="portfolio">
<option selected="selected" value="Select One">Select One</option>
</select>
Share
Improve this question
edited May 14, 2010 at 14:57
Choy
asked May 14, 2010 at 14:34
ChoyChoy
2,11711 gold badges39 silver badges49 bronze badges
1
- FWIW, the title should probably be "Dynamically create DOM object and give class" :-) – T.J. Crowder Commented May 14, 2010 at 14:45
2 Answers
Reset to default 6You can assign class name(s) to the className
property, e.g.:
var opt;
for (var i=0;i<portfolio.length-1;i++) {
opt = new Option(portfolio[i]);
opt.className = "your_class_name_here";
portfolioSelect.options[portfolioSelect.options.length] = opt;
}
This is true of any DOM element. className
reflects the class
attribute on the element (it's named that way because class
is a reserved word in Javascript). The value is exactly like the attribute, which means it can multiple classes separated by spaces.
for (i=0;i<portfolio.length-1;i++) {
var option = new Option(portfolio[i]);
option.setAttribute('class', 'your-class-name');
portfolioSelect.options[portfolioSelect.options.length] = option;
}
本文标签: javascriptDynamically create DOM object and give classStack Overflow
版权声明:本文标题:javascript - Dynamically create DOM object and give class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745623075a2666805.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论