简体   繁体   中英

Change the background color of an <option> with JavaScript

So, I know this seems a simple question but it's breaking my mind.

I have a select menu

<select class="form-control" id="MYID">
<option value="">Selecione...</option>
<option selected="selected" value="1296">OPTION 1</option>
<option value="2313">OPTION 2</option>
<option value="-3">ADD NEW...</option>
</select>

That options value = -3 was added by the controller, so I can't edit with CSS. I wanted to put that option in a different background, using JS. So I tried getting the ID and then the value and then change the color

var option = $('#MYID').val("-3");
option.style.color = "red";

I get: Cannot set property 'color' of undefined

I only found answers to "change color to selected option" and that is not what I want.

That option appears in others dropdowns of the software and the value is always the same, so if there was a more general way to do it it would be awesome.

So, thanks to @CBroe in the comments I found a way that is the best for me cause it's general.

Selects all elements with a value="-3" attribute:

option[value="-3"] {
  background-color: red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM