Css in all options except one

2

I'm trying to apply a css in an option tag. In case you would like only the options that have value starting with 2 to be in blue, like the example below:

$('.select-user option').each(function(){
  if(this.value.startsWith('2')){
    $(this).addClass('option-blue')
  }
})
.select-user{
  width: 200px;
}

.option-blue{
  background-color: blue;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectname="user" class="select-user">
  <option value="1-000">Rosa</option>
  <option value="2-004">José</option>
  <option value="1-001">Maria</option>
  <option value="1-003">Ana</option>
  <option value="2-005">Pedro</option>
  <option value="2-005">Matheus</option>
</select>

However, in this example, I'm adding the class to the option tag directly in the html. How could I select options using only CSS, without the javascript code?

    
asked by anonymous 16.08.2018 / 15:17

1 answer

5

So?

.select-user{
  width: 200px;
}

.select-user > option[value^="2"]{
  background-color: blue;
  color: white;
}
 
<select name="user" class="select-user">
  <option value="1-000">Rosa</option>
  <option value="2-004">José</option>
  <option value="1-001">Maria</option>
  <option value="1-003">Ana</option>
  <option value="2-005">Pedro</option>
  <option value="2-005">Matheus</option>
</select>

The option[value^="2"] excerpt indicates that all elements whose value attribute starts with 2 will be marked with the given style there.

^= has the same effect as the String.startsWith function of Javascript.

I suggest you take a look at this SOEN

The name of this is Attribute Selector and is available from CSS 3.

    
16.08.2018 / 15:26