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?
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.– Bacco
Dude makes sense, I was looking for a way with css, to decrease part of the code.
– N. Dias
This solution posted below by colleague Wallacemaxters is very good, solves with pure CSS.
– Bacco