Home > Web Front-end > CSS Tutorial > How Can I Change the Background Color of a Selected Option in an HTML `` Element?

How Can I Change the Background Color of a Selected Option in an HTML `` Element?

Linda Hamilton
Release: 2024-12-01 07:29:13
Original
659 people have browsed it

How Can I Change the Background Color of a Selected Option in an HTML `` Element?

Customizing the Background Color of the Selected Option in HTML Select

In HTML, the element with a red background is defined, but the selected option remains blue. Attempts to override this behavior using a style like "selected-color" have proven futile. This question delves into the options available to achieve the desired customization.

JavaScript Solution

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template