Home >Web Front-end >CSS Tutorial >How Can I Change the Background Color of a Selected Option in an HTML `` Element?
In HTML, the
In the provided example, a
Pure CSS alone may not suffice in addressing this issue. However, a simple JavaScript solution can elegantly resolve it.
var sel = document.getElementById('select_id'); sel.addEventListener('click', function(el){ var options = this.children; for(var i=0; i < this.childElementCount; i++){ options[i].style.color = 'white'; } var selected = this.children[this.selectedIndex]; selected.style.color = 'red'; }, false);
This crude but effective method ensures that only the selected option retains the specified color, while all others revert to white.
The above is the detailed content of How Can I Change the Background Color of a Selected Option in an HTML `` Element?. For more information, please follow other related articles on the PHP Chinese website!