Css in all options except one

Asked

Viewed 137 times

2

I am trying to apply a css to an option tag. In case I would like only the options that have value starting with 2 stay in blue, as 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>
<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>

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

  • 1

    If you are the one who generates the option (manually or automatically), wouldn’t you just generate the corresponding class at the same time? If you are doing the html "in hand", just by a class="comdois" in the desired ones, if you are generating via programming (PHP, C#, whatever it is) just by this logic of "if started by two put such class" in the loop that generates the options, no? Avoid depending on the end user for this. Or, use pure CSS instead of JS, if it is only the initial 2 that determines, nor need JS.

  • Dude makes sense, I was looking for a way with css, to decrease part of the code.

  • This solution posted below by colleague Wallacemaxters is very good, solves with pure CSS.

1 answer

5


Thus?

.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 excerpt option[value^="2"] indicates that all elements whose attribute value start with 2 will be marked with the style determined there.

The ^= has the same effect as the String.startsWith javascript.

I suggest you take a look at this question from SOEN

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

  • 2

    Vlw, that was it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.