tags:

views:

41

answers:

2

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>
+1  A: 
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;
}
bogdanvursu
Doesn't work on IE. IE's `setAttribute` is a bit broken in this regard and requires "className", not "class". And of course, other browsers (correctly) expect "class", not "className". Whereas using the reflected property (see my answer) is reliable cross-browser.
T.J. Crowder
+2  A: 

You 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.

T.J. Crowder