[Greasemonkey] change background color of options

Nikolas Coukouma lists at atrus.org
Wed Jul 6 10:36:35 EDT 2005


Tobias Orterer wrote:

>hi,
>
>is it possible to change the background color of an single <option>
>element in a select box?
>like (written html):
><select>
><option style="background-color:#FF0000;">&nbsp;&nbsp;&nbsp;</option>
><option style="background-color:#00FF00;">&nbsp;&nbsp;&nbsp;</option>
></select>
>
>
>thats for your help!
>
The above HTML works as you'd expect, at least in Firefox 1.0.4. The
only catch is that once you select the value, the color vanishes. To get
it to work, you have to set the background-color of the select element:
<select style="background-color:#FF0000;">
Obviously you'd want to change it based on the currently selected item.
You can use elm.style.setProperty( "background-color", "#FF0000", "" ),
assuming elm has an HTMLElment object (which is what you get from
getElementByID and such).
The index of the currently selected option is stored in selectedIndex.
options can be quickly accessed via the options proerty.
elm.options[ elm.selectedIndex ]
will yield the currently selected option. The following code sets the
background color of the select element to be the same a s the currently
selected option:
curColor = select.options[ elm.selectedIndex ].style.backgroundColor;
select.style.setProperty( "background-color", curColor, "" )

Object refrences:
http://xulplanet.com/references/objref/HTMLSelectElement.html
http://xulplanet.com/references/objref/HTMLOptionElement.html

-Nikolas Coukouma


More information about the Greasemonkey mailing list