Style element based on selected

Impossible? Hold my beer.

Make the select element aware of the current option. CSS can handle the rest. For this, all we need is a value assignment in the onchange event. With a little more effort you can also initialize the <select> tag by its original value; not included below but it’s super easy, just give it a “data-chosen” property when composing the markup.

    <select onchange=" this.dataset.chosen = this.value; ">
        ...
        ...
    </select>

And now you can easily target & style it:

select[data-chosen='opt3'] { 
    border: 2px solid red;
}

See on CodePen.

Side note: “chosen” is no magic word, just a descriptive name – it could be “SantaClaus”. It would also look better that way.

Leave a Comment