views:

614

answers:

3

Is it possible to set the selected attribute of an option tag via a CSS class?

I'm wondering if something like the following is possible in a stylesheet:

option.selected {
  selected: true;
}

Then in HTML:

<option class="selected">

Which would have the same effect as setting the selected attribute. Is this technique possible?

+7  A: 

Nope, CSS only alters the presentation, not the content (although CSS3 does support some modification of content, but not the selection of values.) You'll need to use JavaScript if you can't modify the HTML directly.

Blixt
This is what I suspected, thanks for the confirmation.
Travis Beale
+2  A: 

Not via CSS, but it can be accomplished via javascript.

function setSelects() {

    var allSelects = document.getElementsByTagName("select");
    for (var i = 0; i < allSelects.length; i++) {
        for (var j = 0; j < allSelects[i].options.length; j++) {
            if (allSelects[i].options[j].className == "selected") {

                allSelects[i].selectedIndex = j;
            }
        }
    }
}

window.onload = setSelects;

As other people have pointed out, I'm not sure why you'd want to do it via a CSS class in the first place.

Matt Bridges
A: 

Selected is not a CSS property. See the spec at http://www.w3.org/TR/CSS2/propidx.html.

tvanfosson