Dynamically create DOM object and give class

I am dynamically creating option elements for a dropdown 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 filled with an external source.

HTML where options are inserted:

<select id="portfolio" name="portfolio">
    <option selected="selected" value="Select One">Select One</option>
</select>

      

+2


a source to share


2 answers


You can assign the class name (s) to the property className

, for example:

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 applies to any DOM element. className

reflects the attribute class

for the element (it named this path because it class

is a reserved word in Javascript). The value matches the attribute exactly, which means that it can contain multiple classes, separated by spaces.

+5


a source


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;
}

      



+1


a source







All Articles