Reputation: 2997
Using Select2js plugin, is it possible to change only the first option's font color in the select element?
I have tried…
select option:first-child { color:red; }
and
$(function() {
$("select option:first-child").addClass("red");
});
.red { color:red; }
Example:
$(function() {
$("select").select2();
$("select option:first-child").addClass("red");
});
.red {color: red;}
select option:first-child {color: red;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<select>
<option>Text 1</option>
<option>Text 2</option>
<option>Text 3</option>
</select>
Upvotes: 1
Views: 385
Reputation: 1074425
If you right-click the select2 options and choose "Inspect" (or "Inspect Element", depending on your browser), you'll see that they aren't option
elements, they're li
elements with the class select2-results__option
in a ul
with the class select2-results__options
.
So:
.select2-results__options li.select2-results__option:first-child {
color: red;
}
Updated Fiddle, or as a Stack Snippet:
$(function() {
$("select").select2();
$("select option:first-child").addClass("red");
});
.select2-results__options li.select2-results__option:first-child {
color: red;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select>
<option>Text 1</option>
<option>Text 2</option>
<option>Text 3</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
If you like, you can further refine the styling for active elements using the class select2-results__option--highlighted
, which is added when elements are "active." For instance, here I've made it blue when it's not active, and red when it is:
$(function() {
$("select").select2();
$("select option:first-child").addClass("red");
});
.select2-results__options li.select2-results__option:first-child {
color: blue;
}
.select2-results__options li.select2-results__option.select2-results__option--highlighted:first-child {
color: red;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select>
<option>Text 1</option>
<option>Text 2</option>
<option>Text 3</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
Upvotes: 3